With PowerShell, you can access the very wide range of objects from the .NET class libraries. This means you can access directly the functionality provided by the methods in these various objects. Dave Donaldson posted his discovery of this in his article Running .NET Code from PowerShell Scripts. Old PowerShell hands (and readers of my script blog are familiar with this. I find it pretty cool that you can reach into .NET to use it’s features directly in your PowerShell scripts.
In addition, if you write a library of managed code, you can use the objects/methods in that add-on code. Donaldson discusses his use of the SharpZibLib library. This library is a Zip, Gzip, Tar, BZip2 library written in C#. This library is free (released under the GPL). One cool thing about this library is that you can use it to create commercial closed source apps. You can download the binaries (there’s one for .NET 1.1, .NET 2.0, as well as .NET CF 1.0 and .NET CF 2.0), the course code or a help file.
With this library, you can easily create and manipulate zip files. I’ve used this in a script I’ve developed that zips up the script files in my PowerShell Script library and uploads them to http://www.reskit.net/powershell/scriptlib.zip). I’ll publish the full script once I finish it off!
To show the use of this external library here’s the basic bit of script I use to create the zip file:
# First, load the zip library [void] [System.Reflection.Assembly]::LoadFrom("C:\foo\bin\ICSharpCode.SharpZipLib.dll") # Now create a new zip file object $zip = new-object ICSharpCode.SharpZipLib.Zip.FastZip # Define what to zip and from where $zipfile = "C:\Foo\PSScriptLib.Zip" $zipfrom = "E:\PowerShellScriptLib" $recurse = "true" $ziptoadd = ".ps1" # Now create the zip file $zip.CreateZip($zipfile, $zipfrom, $recurse, $ziptoadd) ls $zipfile
This script first loads the library using System.Reflection.Assembly. Once the assembly is loaded, we create a new object representing a zip file. The script then defines what to zip, and where we to put the zip file. Then we use the CreateZip method to add all the .PS1 files in E:\PowerShellScriptLib (and below) into the zip file that ends up in C:\Foo\PSScriptlib.Zip. The script finishes by performing a directory listing of the newly created zip file.
Running this bit of code produces something like this:
PS C:\foo> .\ZipScriptLib.ps1' Directory: Microsoft.PowerShell.Core\FileSystem::C:\foo Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 11/30/2008 11:37 AM 51816 PSScriptLib.ZIP
Of course, that’s only the first step. I’ll need to use the SharpZipLib to add a “readme” file to the archive and I’ll need to upload the zip file to my web site. I’ll cover these aspects in a later blog post!