What can I do with C# and Powershell?

Kredns picture Kredns · Apr 12, 2009 · Viewed 55.4k times · Source

I have a decent understanding of C# and a very basic understanding of powershell. I'm using Windows PowerShell CTP 3, which has been really fun. But I want to go beyond writing scripts/functions. Is there any cool stuff to do with C#?

Answer

Scott Weinstein picture Scott Weinstein · Apr 12, 2009

At the highest level you have two different options You can from a C# program host PowerShell and execute PowerShell commands via RunSpaces and pipelines.

Or you can from within PowerShell run C# code. This can be done two ways. With a PowerShell snapin, a compiled dll which provides PowerShell cmdlets and navigation providers, or via the new cmdlet Add-Type, which lets you dynamically import C#, VB, F# code. From the help

$source = @"
public class BasicTest
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

    public int Multiply(int a, int b)
    {
        return (a * b);
    }
}
"@

Add-Type -TypeDefinition $source
[BasicTest]::Add(4, 3)
$basicTestObject = New-Object BasicTest 
$basicTestObject.Multiply(5, 2)