PowerShell Scripts, Tips, Expert Advices, Forums, and Resources

Geek Sync Live

Welcome to PowerShell.com, the educational and community site for Windows PowerShell People. Get a quick overview.


As a Powershell.com member you will have access to:

  • Daily PowerShell tips written by Microsoft MVPs and other leading Windows PowerShell experts
  • Free Windows PowerShell advice and training provided by Microsoft MVPs and other leading Windows PowerShell experts
  • Access to leading Windows PowerShell blogs
  • A free ebook, Mastering PowerShell, written by Microsoft MVP Dr. Tobias Weltner
PowerTip of the Day

Create Benign “Task Kill” Application

In a previous tip we showed how you can select applications and kill them immediately. All unsaved data in the applications would get lost.

Here is a more sophisticated approach. It lists all applications, and you can select those you want to end (hold CTRL to select multiple applications).

The script then tries and close the selected applications by sending a “close window” message. The user gets a chance to save unsaved data. The user can also cancel the “close window” message, though.

This is why the script waits for 15 seconds, and then checks whether the requested applications actually ended. If not, these applications are killed immediately (remove –WhatIf to actually kill them):

#requires -Version 3

$list = Get-Process | 
    Where-Object -FilterScript {
        $_.MainWindowHandle -ne 0 
    } |
    Select-Object -Property Name, Description, MainWindowTitle, Company, ID |
    Out-GridView -Title 'Choose Application to Kill' -PassThru 

# try and close peacefully
$list.ID | ForEach-Object -Process { 
    $process = Get-Process -Id $_
    $null = $process.CloseMainWindow()  
}

# give user 15 seconds to respond
Start-Sleep -Seconds 15

# check to see if selected programs closed, and if not, kill
# them anyway (remove -WhatIf to actually kill them)
$list.ID | 
ForEach-Object -Process {
    Get-Process -Id $_ -ErrorAction SilentlyContinue 
    } |
    Where-Object -FilterScript {
        $_.hasExited -eq $false 
    } |
    Stop-Process -WhatIf

Twitter This Tip! ReTweet this Tip!

Copyright 2012 PowerShell.com. All rights reserved.