What can I do with C# and Powershell?


Question

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#?

1
45
10/14/2011 9:37:53 AM

Accepted Answer

I think the most interesting thing you can do with C# and PowerShell is to build CmdLet's. These are essentially plugins to PowerShell that are written in managed code and act like normal functions. They have a verb-noun pair and many of the functions you already use are actually cmdlets under the hood.

http://msdn.microsoft.com/en-us/magazine/cc163293.aspx

34
3/6/2012 9:59:59 PM

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)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon