Charles Anderson
Charles Anderson

Reputation: 20039

Is there a gentle way of stopping processes using Windows 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 ...")

Upvotes: 17

Views: 7908

Answers (3)

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

Roman Kuzmin
Roman Kuzmin

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

Keith Hill
Keith Hill

Reputation: 201652

Try this to simulate the user closing the app:

(Get-Process -Id 10024).CloseMainWindow()

Upvotes: 16

Related Questions