Posts RSS Comments RSS 253 Posts and 411 Comments till now

Kill-UserProcess (my first whatif Script)

There was a post on the forums about Killing all the processes for a user so I decided to write a script for it… sounded like something I could use. I thought about using get-process or [System.Diagnostics.Process] for remoting, but instead I went with WMI.

Below is the script and here are some example usages

Get User Processes on Server
PS> kill-userProcess -server Serverx -user jloser
Get User Processes on Server and Kill using -whatif
PS> kill-userProcess -server Serverx -user jloser -kill -whatif
Get User Processes on Server and kill them
PS> kill-userProcess -server Serverx -user jloser -kill
Get User Process on Server Kill/Whatif
PS> kill-userProcess -server Serverx -user jloser -process explorer.exe -kill -whatif
Get User Process on Server just kill
PS> kill-userProcess -server Serverx -user jloser -process explorer.exe -kill

[code]
function Kill-UserProcess{
param([string]$server,[string]$user,[string]$process,[switch]$Kill,[switch]$whatif)
if($server){$processes = Get-WmiObject Win32\_Process -ComputerName $server}
else{$processes = Get-WmiObject Win32\_Process}
if($user){
if($kill){if(!$process){Write-Host “Killing all Processes for User [$user]”}}
foreach($p in $processes){
if($p.GetOwner().user -match “$user”){
if($process){
if($p.Name -match “$process”){
if($kill){
Write-Host “Killing Process [$($p.Name)] for User [$user]”
if($whatif){
write-Host “What if: Performing operation “”kill”” on Target “”$($p.Name)””.”
}
}
else{
Write-Host “Killing Process $($p.Name)”
$p.Terminate() | out-null
}
return $true
}
}
if($kill){
if($whatif){
write-Host “What if: Performing operation “”kill”” on Target “”$($p.Name)””.”
}
else{
Write-Host “Killing Process $($p.Name)”
$p.Terminate() | out-Null
}
}
else{
Write-Host “$p.Name”
}
}
}
}
}
[/code]

One Response to “Kill-UserProcess (my first whatif Script)”

  1. on 03 Mar 2007 at 12:01 pmJeffrey Snover

    Good Stuff!
    You might want to check out: http://blogs.msdn.com/powershell/archive/2007/02/25/supporting-whatif-confirm-verbose-in-scripts.aspx

    I posted a feature-rich library routine to help with -WHATIF, -VERBOSE and -CONFIRM. It might be able to save you some time on your next one.

    Jeffrey Snover [MSFT]
    Windows PowerShell/MMC Architect
    Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
    Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

Trackback this post | Feed on Comments to this post

Leave a Reply

You must be logged in to post a comment.