如何在powershell中实现using语句?

如何在power shell中使用?

这是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) 

谢谢你的帮助。

这是一个解决方案:

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

我发现这个解决方案在这里 ,对我来说它有效。

但它基本上是在finally块中实现dispose。