如何清理$ IE对象,关闭当前进程

时间:2016-05-03 17:05:02

标签: powershell internet-explorer com try-catch hwnd

是否有一个简单的命令来关闭当前IE COM对象作为清理的一部分?

第一次尝试,没有工作:

Try{
  $ErrorActionPreference = "Stop"
  $ie = New-Object -COMObject InternetExplorer.Application
  $ie.visible = $true
  $ie.navigate("www.site.com")
  # do other stuff

}
Catch{
  write-host “Exception Message: $($_.Exception.Message)” -ForegroundColor Red

} 

Finally{
  $ie.Quit() # $ie does not have method Quit()
}

还尝试了以下内容:

Catch{
    Get-Process iexplore | ? {$PID -eq $_.Id} | Stop-Process
}

我所做的一切似乎都无法奏效。我想做的就是关闭当前脚本中的$ ie对象。可能有其他IE进程同时运行,因此我只想关闭我刚刚使用的那个。有什么想法吗?

编辑:为什么在脚本到达Finally {}时,$ ie不再可用?在您引用为重复的帖子中没有回答这个问题。

解决了,有点......但不是真的

$ie = New-Object -COMObject InternetExplorer.Application
$currentIDs = (Get-Process iexplore).Id # how do I only get process IDs of current script?

    Try{
    $ErrorActionPreference = "Stop"

        ... more code ...

    $ie.visible = $true
    $ie.navigate("http://www.allregs.com/tpl/Main.aspx")

        ... more code ...
    }

    Catch{
    write-host “Exception Message: $($_.Exception.Message)” -ForegroundColor Red
    Write-Host "Failed." -ForegroundColor Red 
}

    Finally{
    Get-Process | ? {($_.ProcessName -eq 'iexplore') -and ($_.Id -in $currentIDs )} | Stop-Process
}

这可以解决任何IE进程。问题是我认为这也将关闭可能同时运行的所有其他IE进程。谁能证实这一点?如果是这样,如果有办法只关闭此脚本的当前IE进程?

0 个答案:

没有答案