August 20, 2015

Call inline C# from PowerShell


Windows PowerShell is a shell for task automation and configuration management. The shell is based on the .NET framework and it includes a command-line shell and a scripting language. Features include built-in commands (cmdlets) to manage computers in your network. Cmdlets perform common system administration tasks such as managing the registry; managing event logs; controlling services and processes; and using Windows Management Instrumentation.

Apart from shell's cmdlets, there is also flexibility to use C# code, because the shell is based on .Net framework. In this post I demonstrate a way to call inline C# code from the PowerShell script. Following is the script to do so.


$Source = @"
namespace TestNamespace
{
    public static class MyClass
    {
        public static string GetMessage()
        {
            return "Text from C#";
        }
      
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
}
"@

Add-Type -TypeDefinition $Source -Language CSharp

[TestNamespace.MyClass]::GetMessage()

[TestNamespace.MyClass]::Add(3, 5)

Let review this script:
  • The first statement here you see that we put our C# code in a variable named $source (in PowerShell we define variable by placing $ sign with it).
  • Next we call PowerShell cmdlet Add-Type, here we define -TypeDefinition is our C# class code, and telling the shell that this script is actually C# code defined by the argument -Language CSharp
    These two steps are required, lets say, to register our C# code, so PowerShell can understand it.
    Now its the time to actually call our code and that is pretty straight forward.
  • [TestNamespace.MyClass]::GetMessage() will call our Method which only returns a string.
  • [TestNamespace.MyClass]::Add(3, 5) will accept two integer parameters and return the output as integer.
So here we get C# action in PowerShell.

No comments:

Post a Comment