Wrapping using statement with dispose in powershell

Apr 2, 2013 windows powershell

Today I'm working with zip archives for lambda functions. I needed to take the zip file and add deployment configuration. Lambdas are currently packaged up with their configuration so I need to inject in a file into the zip.

It's relatively trivial to work with compressed zip files in Powershell, however you need to dispose the handle when you've finished with it.

[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
$disposeMe = [System.IO.Compression.ZipFile]::Open($path, "Update");
# ...
$disposeMe.dispose();

A using statement is really just a try catch that calls dispose if the object isn't null. Dave Wyatt's Using-Object: PowerShell version of C#’s “using” statement post has a good example function of where this is all taken care of and uses a $ScriptBlock to execute it.

So instead of manually calling dispose, we can now write a using lookalike, and the handle will be disposed for us. Lovely!

Using-Object ($zip = [System.IO.Compression.ZipFile]::Open($path, "Update")) {
    # ...
}

If you don't want to add the function, you can always just wrap a try catch around it.

try { $disposeMe = [System.IO.Compression.ZipFile]::Open($path, "Update"); }
finally
{
  if ($null -ne $disposeMe -and $disposeMe -is [System.IDisposable]) { $disposeMe.Dispose() }
}