Site Loader
Auckland, New Zealand
Powershell as we know is a platform for distributed automation in Windows environment. It’s very handy for
  • Administrators,
  • Power users
  • Developers and
  • Testers
Since Powershell is tightly integrated with .Net Framework and seamlessly work with all the components of Windows (also Windows Server) it comes powerful with the complete advantages of both the worlds. Windows Server 2012 ships with around 2300+ cmdlets to do faster management of server operations (again useful for all the different kinds of people we discussed) and similarly SQL Server, Office, Entity Framework etc has powershell cmdlets. Enough with history of Powershell, let’s see how we can leverage C# (Another powerful language) code and work within Powershell.

C# in Powershell

C# codes as we is know is the powerful language and when it comes along with Powershell, it become even more powerful. We are going to use following cmdlets and operators in this code snippet
  1. Here-string operator (@” .. “@)
  2. Call operator ( &)
  3. Add-Type
  4. New-Object
I am going to write a simple Calc application which will have both static and instance methods. In order to write a multiline code we should use here-string in powershell as shown
$MyCode = @"
public class Calc
{
    public int Add(int a,int b)
    {
        return a+b;
    }
    
    public int Mul(int a,int b)
    {
        return a*b;
    }
    public static float Divide(int a,int b)
    {
        return a/b;
    }
}
"@
As you could see I have created a Type called Calc which has two instance methods and one static method. Now I should tell Powershell that, I need to add the Calc type to the current Powershell session (Actually every user will have their own powershell session) Here is the code
Add-Type -TypeDefinition $CalcInstance
Once the type is added you can see the type using command New-Object as shown

Calling static method in Powershell

We can call the static method “Divide” with the below command

Calling instance method

As we do in C#, first create the instance of type Calc using New-Object and then call the instance variable to access all the methods
Add-Type -TypeDefinition $CalcInstance
$CalcInstance = New-Object -TypeName Calc
$CalcInstance.Add(20,30)
Here is how your output looks like

Powershell in C#

As we saw above, we leveraged the power of C# in Powershell, but the real power comes while we run powershell command in C#, since powershell does lot of powerful job with simple cmdlets, if we could bring that in C#, it’s going to rock our code!!! Let’s not wait any further and get to the job. All the Powershell related functions are sitting in System.Management.Automation namespace, so guess what’s next you will do, well yes, you are right, reference that in your project!!! Here are the following functions I am going to use in C# to work with Powershell
  1. Powershell.Create()
  2. AddScript()
  3. Invoke()
  4. PSObject
I am not going to detail on any of the above stuffs, since they are pretty easy to figure out yourself by googling J Now here is the code snippet
 static void Main(string[] args)
        {
            var script = "Get-Process | select -Property @{N='Name';E={$_.Name}},@{N='CPU';E={$_.CPU}}";

            var powerShell = PowerShell.Create().AddScript(script);

            foreach (dynamic item in powerShell.Invoke().ToList())
            {
                //check if the CPU usage is greater than 10
                if (item.CPU > 10)
                {
                    Console.WriteLine("The process greater than 10 CPU counts is : " + item.Name);
                }
            }

            Console.Read();
        }
As you could see, I have first written a powershell command which will get the list of process from my machine by selecting only its property named CPU and Name of the Process And then using AddScript() method, I am adding the created script and invoking it in Iterator. I am also using dynamic here (remember Dynamic Language Runtime (DLR)) since C# will not be sure of the properties the executed command is going to give during run-time (which make perfect sense) Now you can see the output as shown below (this will change for you and me J) I hope this will give you an idea of how to use powerful Powershell in C# and vice versa !!! Thanks, Karthik KK

Post Author: Karthik kk

7 Replies to “Calling C# code in Powershell and vice versa”

  1. Wow – i’m definitely going to use this soon. My C# is a bit weaker than my PowerShell; I can now fill in the gaps using PowerShell though!

    Thanks for sharing this 🙂

  2. THANKS dude! I hade some C# Code and wasn’t able to run the methods. This post showed me how easy it is, thanks!

    In software engineering you just spend too much time searching for such little solutions.

  3. I’m looking for a replacement for embedded TCL from C#.

    When using embedded PowerShell from C#, does it have the TCL capability to register a C# method as a native PowerShell command? Because that’s a show stopper for the use of PowerShell as an embedded tool language. I don’t want to create 100 different c# commands, instead have all the command in one assembly and then add them into a tool scripting language such as powershell.. I just don’t know if powershell with fit the same bill as TCL.

  4. Thanks Karthik. I have a free Pluralsight account but I prefer your videos, they are very clear and well prepared.

    A small typo:
    Add-Type -TypeDefinition $CalcInstance
    should be
    Add-Type -TypeDefinition $MyCode

Leave a Reply

Your email address will not be published. Required fields are marked *