Create Benign “Task Kill” Application

by Jul 1, 2015

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!