| Running .NET Code from PowerShell Scripts |
| Tuesday, November 25 2008 |
|
As part of my current automation work, I've been messing around with PowerShell quite a bit. Before now I've only had cursory exposure to PowerShell, but now that I've actually used it, it's pretty sweet and has really grown on me.
One of the things I'm automating is the building and packaging of the Community Server SDK. Up until now, putting the SDK together has been a mix of scripting and manual copying/pasting, with the last step being a manual effort to zip up the package for download. But I didn't want us to continue doing that, as my goal is to automatically build and package the SDK on our build server every night (and of course off-schedule as needed).
I got the PowerShell script doing all the necessary things, but the last remaining item was the zipping up of the package. After some digging I found that PowerShell can invoke code from .NET libraries. Obviously, this opens a huge door to leverage existing functionality from whatever .NET libraries you need.
In my case, I needed functionality from SharpZipLib, the free .NET library that programmatically builds zip files. After a little more reading and experimentation, I came up with this for the part of the PowerShell script that invokes the SharpZipLib library:
| $zipTarget = "D:\Builds\CommunityServerSDK\Drops\" + $sdkFolder + ".zip" $zipSource = "D:\Builds\CommunityServerSDK\Drops\" + $sdkFolder $zipLibraryPath = "D:\Downloads\SharpLibZip\net-20\ICSharpCode.SharpZipLib.dll" [System.Reflection.Assembly]::LoadFrom($zipLibraryPath) $zip = new-object ICSharpCode.SharpZipLib.Zip.FastZip $zip.CreateZip($zipTarget, $zipSource, "true", [string]::Empty) |
A little explanation:
- The $sdkFolder variable is the name of the SDK folder defined higher up in the script.
- The [System.Reflection.Assembly] line uses the LoadFrom method to load the SharpZipLib assembly into the PowerShell process.
- The new-object command creates a new FastZip class from the SharpZipLib assembly.
- The last line invokes the CreateZip method from the FastZip class, passing in string.Empty as the last parameter.
And there you have it. Nothing complex or earth-shattering, but extremely useful, and now for us, completely automated :-)

2 comment(s) so far
Pfft... just wait till you discover Ruby + Rake, mmmm... delicious!
Great to see another PS user. I'm curious as to your approach in the division of work between the build script (msbuild? nant?) and the PowerShell script as some things could be done in either.