Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement using statement in powershell?

Tags:

c#

powershell

How can I write using in power shell ?

This is working example in C#

using (var conn = new SqlConnection(connString)) {     Console.WriteLine("InUsing"); } 

I need same in Powershell (not working):

Using-Object ($conn = New-Object System.Data.SqlClient.SqlConnection($connString)) {      Write-Warning -Message 'In Using';           } 

It is working without using:

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

Thank you for help.

like image 736
Raskolnikov Avatar asked Feb 08 '17 08:02

Raskolnikov


People also ask

What is $using in PowerShell?

Beginning in PowerShell 3.0, you can use the Using scope modifier to identify a local variable in a remote command. The syntax of Using is as follows: $Using:<VariableName> In the following example, the $ps variable is created in the local session, but is used in the session in which the command runs.

How do you use functions in PowerShell?

A function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces. The function shown is a simple example that returns the version of PowerShell.

What does @() mean in PowerShell?

What is @() in PowerShell Script? In PowerShell, the array subexpression operator “@()” is used to create an array. To do that, the array sub-expression operator takes the statements within the parentheses and produces the array of objects depending upon the statements specified in it.

What is PowerShell statement?

If the value of switch-condition matches a pattern value, that pattern's statement-block is executed. If multiple pattern values match the value of switch-condition, each matching pattern's statement-block is executed, in lexical order, unless any of those statement-blocks contains a break statement (§8.5.


1 Answers

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.') } 
like image 167
Bert Levrau Avatar answered Sep 18 '22 15:09

Bert Levrau