Last active
March 13, 2018 21:09
-
-
Save fresh2dev/d5d3431bb7f19518ddcf624a949d5cfb to your computer and use it in GitHub Desktop.
AnyBox Demo - Process Killer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Import-Module AnyBox | |
[string]$default_input = 'localhost' | |
[hashtable]$answer = $null | |
[bool]$continue = $true | |
[hashtable]$common = @{WindowStyle = 'ToolWindow'; Title = 'Process Killer'; CancelButton = 'Cancel'} | |
while ($continue) { | |
$answer = Show-AnyBox @common -Buttons 'Cancel', 'Search' -DefaultButton 'Search' ` | |
-Prompt @( | |
@{ Message = 'Computer Name:'; DefaultValue = $default_input; ValidateScript = { Test-Connection $_ -Count 1 -Quiet -ea 0 }}, | |
@{ Message = 'Process Name Filter:'; DefaultValue = '*'; ValidateNotEmpty=$true } | |
) | |
$continue = $answer['Search'] | |
if ($continue) { | |
$computer_name = $answer['Input_0'] | |
$default_input = $computer_name | |
[string]$filter = $answer['Input_1'].Replace('*', '%') | |
[array]$processes = $null | |
[string]$msg = $null | |
try { | |
$processes = @(Get-WmiObject -cn $computer_name -Class Win32_Process -Filter "Name LIKE '$($filter)'" -ea Stop) | |
if ($processes.Length -eq 0) { | |
$msg = 'No processes match the given filter.' | |
} | |
} | |
catch { | |
$msg = $_.Exception.Message | |
} | |
if ($msg) { | |
$answer = Show-AnyBox @common -Message $("Error: '{0}'" -f $msg) -Buttons 'Cancel', 'Retry' | |
$continue = $answer['Retry'] | |
} | |
else { | |
$answer = Show-AnyBox @common -Buttons 'Cancel', 'Kill' -SelectionMode MultiRow ` | |
-GridData @($processes | select ProcessId, ProcessName, CommandLine) | |
$continue = $answer['Kill'] | |
if ($continue) { | |
[array]$toKill = @($answer['grid_select'] | select ProcessId, ProcessName) | |
$answer = Show-AnyBox @common -Message 'Are you sure you want to', 'kill the following processes?' -HideGridSearch ` | |
-GridData $toKill -Buttons 'Cancel', 'Confirm' | |
$continue = $answer['Confirm'] | |
if ($continue) { | |
[uint32[]]$killIDs = $toKill | select -ExpandProperty ProcessId | |
$results = $processes | where { $killIDs -contains $_.ProcessId } | foreach { | |
[int]$code = 0 | |
[string]$msg = $null | |
try { | |
$code = $_.Terminate().ReturnValue | |
if ($code -eq 0) { | |
$msg = 'Successfully closed.' | |
} | |
} | |
catch { | |
$msg = $_.Exception.Message | |
} | |
$_ | select ProcessId, ProcessName, @{Name='Code';Expression={$code}}, @{Name='Message';Expression={$msg}} | |
} | |
$answer = Show-AnyBox @common -Buttons 'Cancel', 'Run Again' -HideGridSearch -GridData $results | |
$continue = $answer['Run Again'] | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment