Is there a gentle way of stopping processes using Windows PowerShell?
I have to stop a browser from a Powe开发者_开发知识库rShell script, which I do by piping it into
Stop-Process -Force
However, this is very abrupt. When the browser is restarted, it detects that it didn't shut down cleanly, and tries to restart the previous session. Is there some way I can tell it to shut itself down gracefully? ("There are two ways we can do this ...")
Try this to simulate the user closing the app:
(Get-Process -Id 10024).CloseMainWindow()
Keith Hill has already proposed to use CloseMainWindow(). But it is only an invitation to close, some user interaction still might be needed, for example an application may show some dialogs to save something and etc. If a calling script really expects a process to be exited, I use this pattern:
# close the window and wait for exit
$_ = Get-Process -Id 12345
[void]$_.CloseMainWindow()
if (!$_.HasExited) {
Write-Host "Waiting for exit of Pid=$($_.Id)..."
$_.WaitForExit()
}
You can also do this:
Get-Process <name> | where {$_.MainWindowHandle -ne [System.IntPtr]::Zero} | foreach {$_.CloseMainWindow()}
This will close all processes that match the pattern and have a window attached to them. For example, Chrome process may use subprocesses that do not have a window. These subprocesses will be ignored.
精彩评论