Skip to content

Instantly share code, notes, and snippets.

@jeremybeavon
Created April 7, 2015 03:20
Show Gist options
  • Save jeremybeavon/a63e563e564e160b18cc to your computer and use it in GitHub Desktop.
Save jeremybeavon/a63e563e564e160b18cc to your computer and use it in GitHub Desktop.
Provides a C#-style using statement for Powershell. Taken from https://davewyatt.wordpress.com/2014/04/11/using-object-powershell-version-of-cs-using-statement/
function Using-Object
{
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[AllowEmptyString()]
[AllowEmptyCollection()]
[AllowNull()]
[Object]
$InputObject,
[Parameter(Mandatory = $true)]
[scriptblock]
$ScriptBlock
)
try
{
. $ScriptBlock
}
finally
{
if ($null -ne $InputObject -and $InputObject -is [System.IDisposable])
{
$InputObject.Dispose()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment