A gentler method to stop a process

I’m currently writing a script that needs to close Outlook before continuing. I’m not a fan of using Stop-Process to close Outlook, as it’s one of those applications that likes to do its own shutdown process and close data files, etc.

Here’s a little snippet that I’ve done some preliminary testing on, and it seems to work nicely:

do {
    $processes = Get-Process OUTLOOK -ErrorAction SilentlyContinue
    $processes | ForEach-Object {$_.CloseMainWindow()}
    } 
until ($processes -eq $null)

This uses the Process.CloseMainWindow method, which “closes a process that has a user interface by sending a close message to its main window”

When a process is executing, its message loop is in a wait state. The message loop executes every time a Windows message is sent to the process by the operating system. Calling CloseMainWindow sends a request to close to the main window, which, in a well-formed application, closes child windows and revokes all running message loops for the application. The request to exit the process by calling CloseMainWindow does not force the application to quit. The application can ask for user verification before quitting, or it can refuse to quit.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s