40

How can I write a using block in PowerShell?

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';          
}

It is working without a using block:

$conn = New-Object System.Data.SqlClient.SqlConnection($connString)

Thank you for helping.

SendETHToThisAddress
  • 2,756
  • 7
  • 29
  • 54
Raskolnikov
  • 3,791
  • 9
  • 43
  • 88

1 Answers1

60

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.')
}
KyleMit
  • 30,350
  • 66
  • 462
  • 664
Bert Levrau
  • 975
  • 8
  • 11
  • Thank you. Could you explain me what you mean by $ErrorActionPreference ? – Raskolnikov Feb 08 '17 at 09:00
  • 2
    by default the $ErrorActionPreference is set to Continue, then in a try catch you will only trap crittical error's. (you actualy only trap errors that stop the current flow) you can override the error action with commandlets if you you use -erroraction. but I made a mistake here, you don't use the catch block so you don't need to adjust the error action preference. I 'll edit the answer! – Bert Levrau Feb 08 '17 at 09:34
  • I'd add a switch parameter to throw an exception if IDisposable isn't implemented (if not null). Otherwise, the program continues with the object not being released. I'd also add an output variable. As far as I can see, you won't be able to return anything. – Tyler Montney Dec 09 '21 at 17:11
  • 1
    You can simplify this a bit, the `-is` operator works just like in .NET. If you ask of a `null` value if it is of any type it will always return `false`. In other words, the `-is` operator does the `null` check as well. – Andrei15193 Nov 21 '22 at 09:26