如何在Powershell中实现using语句? [英] How to implement using statement in powershell?

查看:89
本文介绍了如何在Powershell中实现using语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Power Shell中使用using?

How can I write using in power shell ?

这是C#中的有效示例

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

我需要在Powershell中使用它(不能正常工作):

I need same in Powershell (not working):

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

    Write-Warning -Message 'In Using';          
}

它可以不使用而工作:

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

感谢您的帮助.

推荐答案

这里是,其最终通过调用 .Dispose()阻止:

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

这是使用方法:

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

这篇关于如何在Powershell中实现using语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆