Reputation: 20039
I have to stop a browser from a PowerShell 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 ...")
Upvotes: 17
Views: 7908
Reputation: 79
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.
Upvotes: 3
Reputation: 42033
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()
}
Upvotes: 11
Reputation: 201652
Try this to simulate the user closing the app:
(Get-Process -Id 10024).CloseMainWindow()
Upvotes: 16