ASP.NET Weblogs

Welcome to ASP.NET Weblogs Sign in | Join | Help
in Search

The Technical Adventures of Adam Weigert

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.

Published Aug 27 2008, 11:56 AM by adweigert
Filed under: ,

Comments

 

choy said:

brilliant. love it.

September 16, 2008 1:32 PM
 

Multi-Purpose PowerShell Using Function « Solutionizing .NET said:

Pingback from  Multi-Purpose PowerShell Using Function « Solutionizing .NET

September 21, 2008 6:19 PM
 

Using IDisposable Objects in PowerShell « Second Stanza said:

Pingback from  Using IDisposable Objects in PowerShell « Second Stanza

December 27, 2008 10:51 PM