This is a working example in C#:
using (var conn = new SqlConnection(connString))
{
Console.WriteLine("InUsing");
}
I need the same in PowerShell (not working):
Using-Object ($conn = New-Object System.Data.SqlClient.SqlConnection($connString)) {
Write-Warning -Message 'In Using';
}
The term 'Using-Object' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
It is working without a using block:
$conn = New-Object System.Data.SqlClient.SqlConnection($connString)
But then, I must remember to close the connection explicitly, even when exceptions are thrown.
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.')
}