Skip to content

51. Embedding Managed Code (C# | VB)

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

  • TypeDefinition : Accepts the code as a string
  • Language : Specifies the Managed Code language.Accepted values: CSharp, CSharpVersion3, CSharpVersion2, VisualBasic, JScript

This topic is to briefly describe how C# or VB .NET Managed code can be scripted and utilised within a PowerShell script. This topic is not exploring all facets of the Add-Type cmdlet. For more information on the Add-Type cmdlet, please refer to the MSDN documentation (for 5.1) here:

https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/add-type

51.1: C# Example

This example shows how to embed some basic C# into a PowerShell script, add it to the runspace/session and utilise the code within PowerShell syntax.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
$code = "
  using System;
  namespace MyNameSpace
  {
  public class Responder
  {
  public static void StaticRespond()
  {
Console.WriteLine("Static Response");
  }
  public void Respond()
  {
Console.WriteLine("Instance Respond");
  }
  }
}"
@
# Check the type has not been previously added within the session, otherwise an exception is raised
if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type)
{
  Add-Type -TypeDefinition $code -Language CSharp;
} [
MyNameSpace.Responder]::StaticRespond();
$instance = New-Object MyNameSpace.Responder;
$instance.Respond();

51.2: VB.NET Example

This example shows how to embed some basic C# into a PowerShell script, add it to the runspace/session and utilise the code within PowerShell syntax.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$code = @"
Imports System
Namespace MyNameSpace
Public Class Responder
Public Shared Sub StaticRespond()
Console.WriteLine("Static Response")
End Sub
Public Sub Respond()
Console.WriteLine("Instance Respond")
End Sub
End Class
End Namespace
"@

# Check the type has not been previously added within the session, otherwise an exception is raised
if (-not ([System.Management.Automation.PSTypeName]'MyNameSpace.Responder').Type)
{
  Add-Type -TypeDefinition $code -Language VisualBasic
}
[MyNameSpace.Responder]::StaticRespond()
$instance = New-Object -TypeName MyNameSpace.Responder
$instance.Respond()