Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a gentle way of stopping processes using Windows PowerShell?

Tags:

powershell

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 ...")

like image 329
Charles Anderson Avatar asked Apr 27 '10 16:04

Charles Anderson


2 Answers

Try this to simulate the user closing the app:

(Get-Process -Id 10024).CloseMainWindow()
like image 199
Keith Hill Avatar answered Nov 06 '22 22:11

Keith Hill


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()
}
like image 28
Roman Kuzmin Avatar answered Nov 06 '22 20:11

Roman Kuzmin