The “Using” Statement In Powershell

When we do code in c#, we have using statement to dispose our objects. so we don’t have to. :).  What about PowerShell? Can we do that?

Here is a PowerShell function which behaves as using statement. 🙂

Function Using-Object(
[System.IDisposable]
$InputObject,
[scriptblock]
$ScriptBlock = {throw "ScriptBlock is mandatory, please provide a value."})
{
try
{
. $ScriptBlock
}
finally
{
if ($null -ne $InputObject -and $InputObject -is [System.IDisposable])
{
$InputObject.Dispose()
}
}
}

view raw
using-statement.ps1
hosted with ❤ by GitHub

So whenever we are dealing with an object that should be disposed we can use this function as below.

# $Connection object will be diposed.
UsingObject($Connection = New-Object System.Data.SQLClient.SQLConnection($ConnectionString)) {
#code goes here.
}

view raw
using-using.ps1
hosted with ❤ by GitHub

Isn’t that cool? 🙂

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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