如何在Powershell中实现using语句?

拉斯科尼科夫:

我该如何在Power Shell中使用using?

这是C#中的工作示例

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

我在Powershell中需要同样的功能(无法正常工作):

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

    Write-Warning -Message 'In Using';          
}

它无需使用即可工作:

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

谢谢你的帮助。

伯特·勒夫劳(Bert Levrau):

这是Using-Object的一种解决方案:C#的“ using”语句的PowerShell版本,其通过调用.Dispose()finally块而起作用

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

以及使用方法:

Using-Object ($streamWriter = New-Object System.IO.StreamWriter("$pwd\newfile.txt")) {
    $streamWriter.WriteLine('Line written inside Using block.')
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章