Stopping Programs Gracefully

by May 27, 2010

While Stop-Process will stop a process immediately in PowerShell, it will also destroy all data that hasn't yet been saved. You can try a more graceful approach that would give the user a warning and allow them to save data:

$proc = Get-Process notepad -ErrorAction SilentlyContinue
$proc| ForEach-Object { $_.CloseMainWindow() } | Out-Null
Start-Sleep -Seconds 15
$proc | Where-Object { $_.hasExited -ne $true } |
Stop-Process -ErrorAction SilentlyContinue -whatif

The user will then get 15 seconds to save all unsaved data. All processes that still run after 15 seconds will be killed.

Twitter This Tip! ReTweet this Tip!