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.
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.
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 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.
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.
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.') }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With