How to implement using instructions in powershell?

How can I write use in a power shell?

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 works without using:

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

Thank you for your help.

+13
c # powershell
source share
1 answer

Here is the solution:

 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() } } } 

I found this solution here and it worked for me.

But this is basically an implementation of the utility in the finally block.

+17
source share

All Articles