PowerShell Tip: Gracefully close a process

Page content

Killing a process is easily done by using the cmdlet Stop-Process, but it has a tendency to stop those processes somewhat ungracefully.

Lets take an example of using notepad.exe This script will start a new instance of notepad.exe, enters some important data and waits for three seconds:

add-type -AssemblyName microsoft.VisualBasic
add-type -AssemblyName System.Windows.Forms

$Process = Start-Process notepad.exe -PassThru
Start-Sleep -Milliseconds 500
[Microsoft.VisualBasic.Interaction]::AppActivate($Process.Id)
[System.Windows.Forms.SendKeys]::SendWait("This is some some important data")
Start-Sleep -Seconds 3

Now that we have a process with some unsaved data lets get to the point.

The easiest way to shut down notepad is by using the cmdlet stop-process, but as mentioned before this will kill the process ungracefully and our “important data” is forever lost.

Instead there is a static method on the process object called CloseMainWindow that will gracefully try to close the window. Since our important data is unsaved notepad will ask if we want to save the changes before exiting.

$Process.CloseMainWindow()

Now answering that question is a topic for another post.