How to implement using statement in powershell?

前端 未结 1 1681

How can I write using in power shell ?

This is working example in C#

using (var conn = new SqlConnection(connString))
{
    Console.WriteLine(\"InUsi         


        
相关标签:
1条回答
  • 2020-12-15 04:58

    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.')
    }
    
    0 讨论(0)
提交回复
热议问题