PowerShell: Adding the Using Statement

So, I happened to come across a need for the using statement from C#. I basically didn't want to use Try...Finally when I am so used to the short-hand using statement. Thank goodness I already have a Try..Catch..Finally statement/function for PowerShell, I can just use that existing framework and make a using statement/function pretty easily.

function Using {
    param (
        [System.IDisposable] $inputObject = $(throw "The parameter -inputObject is required."),
        [ScriptBlock] $scriptBlock = $(throw "The parameter -scriptBlock is required.")
    )
    
    Try {
        &$scriptBlock
    } -Finally {
        if ($inputObject -ne $null) {
            if ($inputObject.psbase -eq $null) {
                $inputObject.Dispose()
            } else {
                $inputObject.psbase.Dispose()
            }
        }
    }
}

# Short example ... 
Using ($user = $sr.GetDirectoryEntry()) { 
  $user.displayName = $displayName 
  $user.SetInfo() 
} 

Update: Take note on variable scope, variables in the using statement will not be available outside of it, this can make it tricky, but it should be easy enough to work with.

1 Comment

Comments have been disabled for this content.