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#?
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.
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)
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.
You can look at it one of two ways:
- How can you leverage PowerShell inside your C# program
- How can you leverage C# programming inside PowerShell.
To some degree, they are quite different questions with different answers.
From C# you can leverage the PowerShell engine, runspaces, pipe-lines, etc. As is done with Exchante, you can use C# to do all the GUI stuff, then invoke a PowerShell cmdlet to do all the hard stuff. This option is appropriate if you can find PowerShell cmdlets or scripts to leverage.
From PowerShell, you use C# to expand what you can do in PowerShell. You can create cmdlts and providers to enable others to access application data. Or you can just create objects that can be used within a PowerShell script. This option is the way you help to open up your application to be managed in a more automated way.
So depending on what you are looking to do, you have options.
Scott Hanselman aka Hanselminutes has several podcasts about Powershell, CmdLets, C# and more. It's the best if you want to learn what it is, how it works and more. Do a search on his website to grab the podcast.
List of PS related podcasts on his site (in reverse chronological order):
#190: State of Powershell/Lee Holmes & Jason Shirk
#162: Powershell 2.0
#49: Powershell/Bruce Payette
#36: Jeffrey Snover, Powershell architect
#24: Windows Powershell (MONAD), Part II
© 2022 - 2024 — McMap. All rights reserved.