PowerShell发布COM对象

Ste*_*e B 6 powershell

我在一个PowerShell脚本中有一个小实用程序函数:

function Unzip-File{
    param(
        [Parameter(Mandatory=$true)]
        [string]$ZipFile,
        [Parameter(Mandatory=$true)]
        [string]$Path
    )

    $shell=New-Object -ComObject shell.application

    $zip = $shell.namespace($ZipFile)
    $target = $shell.NameSpace($Path)
    $target.CopyHere($zip.Items())
}
Run Code Online (Sandbox Code Playgroud)

我应该清理脚本中的COM对象吗?或者PowerShell足够智能自动垃圾COM对象?

我已经阅读了摆脱COM对象(一劳永逸)盲目应用:

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($zip)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($target)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)
Run Code Online (Sandbox Code Playgroud)

但我不确定这是否需要.

在本地函数中使用COM对象的正确模式是什么?

CB.*_*CB. 9

通常我使用这个函数:

function Release-Ref ($ref) {

[System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) | out-null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

}
Run Code Online (Sandbox Code Playgroud)

因为我注意到我的 comobject 总是保持活动状态,我认为 Powershell 2.0 无法删除不再使用的 comobject。

[System.Runtime.InteropServices.Marshal]::ReleaseComObject( $ref )
Run Code Online (Sandbox Code Playgroud)

(参见此处)返回与对象关联的 RCW 的引用计数的新值。此值通常为零,因为 RCW 只保留对包装的 COM 对象的一个​​引用,而不管调用它的托管客户端的数量。我已经注意到,因为shell.application您需要调用它,直到该值变为 0。

要测试是否所有引用都被释放,您可以尝试在值为 0 时读取 $shell 的值:它返回一个错误..