IDisposable and PowerShell versions

I’ve been working on a new module over the past few days, with the intention of having it work on PowerShell 2.0 and later. I did my development and testing on PowerShell 4.0 (.NET 4.5), and when it came time to test on PowerShell 2.0, I ran into an error that basically said “There’s no Dispose() method on object such-and-such.”

My code looked like this:

$someObject = $null
    $someObject = New-Object SomeClass
    if ($null -ne $someObject) { $someObject.Dispose() }

I’ve used this same construct hundreds of times, and it works fine so long as you’re using a consistent .NET Framework version. The problem was that some of the classes started to implement IDisposable in .NET 4.0, but didn’t have that interface previously. I was all set to get annoyed about this, when an easy solution dawned on me:

    if ($someObject -is [IDisposable]) { $someObject.Dispose() }

PowerShell’s -is operator returns false anytime the left operand is null, so a separate check for $null isn’t even necessary. When the code runs on PowerShell 2.0, even if the object is non-null, it still won’t try to call the non-existent Dispose() method.

I did come across one slightly irritating exception to this rule. The System.Security.Cryptography.AesCryptoServiceProvider class for some reason claims that it implements the IDisposable interface, but still doesn’t have a publicly accessible Dispose() method in .NET 2.0. For that specific case, I just went back to checking for null, and called Clear() instead of Dispose(). This may also apply to other Crypto classes; I haven’t checked.


About Dave Wyatt

Microsoft MVP (PowerShell), IT professional.
This entry was posted in PowerShell. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s