gpt4 book ai didi

PowerShell发布COM对象

转载 作者:行者123 更新时间:2023-12-04 14:46:07 26 4
gpt4 key购买 nike

我在一个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())
}

我应该清理脚本中的COM对象吗?还是PowerShell足够聪明,可以自动对COM对象进行垃圾处理?

我读过 Getting Rid of a COM Object (Once and For All)并盲目应用:
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($zip)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($target)
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($shell)

但是我不确定是否需要这样做。

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

最佳答案

通常我使用此功能:

function Release-Ref ($ref) {

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

}

因为我已经注意到我的comobject始终处于事件状态,所以我认为Powershell 2.0无法删除不再使用的comobject。
[System.Runtime.InteropServices.Marshal]::ReleaseComObject( $ref )

(请参阅 here)返回与对象关联的RCW的引用计数的新值。该值通常为零,因为RCW仅保留对包装的COM对象的一个​​引用,而不管调用它的受管客户端的数量如何。
我注意到对于 shell.application,您需要对其进行调用,直到该值变为0为止。

要测试是否释放了所有引用,可以尝试在value为0时读取$ shell的值:它返回错误。

关于PowerShell发布COM对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19029850/

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