Tuesday, February 8, 2011

Q: Is there a PowerShell equivalent to the C# "using" statement (for auto-disposing disposable objects)?

A: No. However, the PowerShell team very kindly came up with a simple implementation, detailed here:

Reserving keywords - Windows PowerShell Blog - Site Home - MSDN Blogs

It looks like this:

function using
{
param($obj, [scriptblock]$sb)

try {
& $sb
} finally {
if ($obj -is [IDisposable]) {
$obj.Dispose()
}
}
}

Here's the example:

using ($stream = new-object System.IO.StreamReader $PSHOME\types.ps1xml) {
foreach ($_ in 1..5) { $stream.ReadLine() }
}

0 comments: