Database PowerShell+;微星。如何释放打开的数据库?

Database PowerShell+;微星。如何释放打开的数据库?,database,com,powershell,windows-installer,Database,Com,Powershell,Windows Installer,我有VB脚本: ..... Set oInstaller = CreateObject("WindowsInstaller.Installer") Set otempDB = oInstaller.OpenDatabase(sMsiFullPathTemp, 1) ....... Set otempDB = Nothing 在这个字符串处,它释放数据库:Set otempDB=Nothing 我需要使PowerShell脚本像这个VBS与MSI的工作 PowerShell: .... fun

我有VB脚本:

.....
Set oInstaller  = CreateObject("WindowsInstaller.Installer")
Set otempDB = oInstaller.OpenDatabase(sMsiFullPathTemp, 1)
.......
Set otempDB = Nothing
在这个字符串处,它释放数据库:Set otempDB=Nothing

我需要使PowerShell脚本像这个VBS与MSI的工作

PowerShell:

....
function Invoke-Method ($Object, $MethodName, $ArgumentList) {
    return $Object.GetType().InvokeMember($MethodName, 'Public, Instance, InvokeMethod', $null, $Object, $ArgumentList)
}
$oInstaller = New-Object -ComObject WindowsInstaller.Installer
$otempDB = Invoke-Method $oInstaller OpenDatabase  @($tempmsi, 1)
但我如何才能释放MSI数据库,直到脚本还并没有完成工作? 我的意思是:Set otempDB=Nothing

有人能帮我吗


谢谢

您始终可以将变量分配给$null:

$otempDB = $null
但是对于COM对象,这通常会导致对象被拖到某个地方的边缘。更好的方法是显式释放对象并清理内存:

([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$otempDB) -gt 0)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
不久前,我在某个地方遇到了一个函数(如果有人知道谁最初发布了这个函数,请留下评论,我会将其归为属性)。我几乎每次使用COM对象时都会使用它:

function Release-Ref ($ref) {

    ([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0)
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()

}

这两个System.GC调用似乎不必要,不赞成不必要地引发垃圾收集器。调用ReleaseComObject是答案的重要部分。您可能是对的。不过,我的经验是,在处理COM对象时,您永远不会有太大的大象枪。检查ReleaseComObject是否返回0可能是值得的。如果没有,请尝试找出原因,而不是重复调用它,直到它返回0。