作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
如何在 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/
我是一名优秀的程序员,十分优秀!