这是另一种方法:
(get-interface $obj ([IDisposable])).Dispose()
Get-Interface 脚本可在此处找到http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx,并在此响应中提出。
使用 'using' 关键字,我们得到:
$MY_DIR = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
# http://www.nivot.org/2009/03/28/PowerShell20CTP3ModulesInPracticeClosures.aspx
. ($MY_DIR + '\get-interface.ps1')
# A bit modified code from http://blogs.msdn.com/powershell/archive/2009/03/12/reserving-keywords.aspx
function using
{
param($obj, [scriptblock]$sb)
try {
& $sb
} finally {
if ($obj -is [IDisposable]) {
(get-interface $obj ([IDisposable])).Dispose()
}
}
}
# Demo
using($writer = [System.Xml.XmlWriter]::Create('c:\some.xml')) {
}