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]
tshell :: Mar.03.2007 ::
Powershell ::
No Comments »