Here is a solution from Using-Object: PowerShell version of C#’s “using” statement which works by calling .Dispose()
in a finally block:
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()
}
}
}
And here’s how to use it:
Using-Object ($streamWriter = New-Object System.IO.StreamWriter("$pwd\newfile.txt")) {
$streamWriter.WriteLine('Line written inside Using block.')
}