gpt4 book ai didi

c# - 如何在powershell中实现using语句?

转载 作者:可可西里 更新时间:2023-11-01 02:59:25 25 4
gpt4 key购买 nike

如何在 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)

谢谢你的帮助。

最佳答案

这是来自 Using-Object: PowerShell version of C#’s “using” statement 的解决方案它通过在 finally block 中调用 .Dispose() 来工作:

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.')
}

关于c# - 如何在powershell中实现using语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42107851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com