Created
April 7, 2015 03:20
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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