PowerShell and IDisposable

Hi folks

C# has a nice syntactic sugar

using (var myDisposable = new MyDisposable())
{
    // ...
}

which corresponds to

MyDisposable myDisposable = null;
try
{
    myDisposable = new MyDisposable()
    // ...
}
finally
{
    if (myDisposable != null)
        myDisposable.Dispose()
}

Let’s implement the same thing for PowerShell

function PSUsing
{
    param
    (
        [IDisposable] $disposable,
        [ScriptBlock] $scriptBlock
    )

    try
    {
        & $scriptBlock
    }
    finally
    {
        if ($disposable -ne $null)
        {
            $disposable.Dispose()
        }
    }
}

We could not use Using because it is a reserved PowerShell word.

And we can use it like

PSUsing ($myDisposable = New-Object -TypeName MyDisposable) `
{
    # ...
}

Stay tuned

Advertisements

About mnaoumov

Senior .NET Developer in Readify
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

One Response to PowerShell and IDisposable

  1. Pingback: Get exif metadata with PowerShell | mnaoumov.NET

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s