A follow on to my previous post. It's great to be able to find a specific copy of a process running on a remote machine (UserA's copy of Notepad, for instance), but the real benefit is being able to do something about it.
Below is
kill_processes.ps1. You'll note that it's nowhere near as clean as my
pkill for windows script. It turns out that to do much of anything on a remote machine with PowerShell, you need to go through WMI. Basically, this script is a more flexible version of the kill scripts. This one takes four parameters:
- computername -- defaults to localhost
- notuser -- this is a pattern for users to ignore. defaults to SERVICE or SYSTEM
- user -- this is a pattern for users to find. It is required, and throws an exception if not provided
- name -- this is a pattern for the process name to find and kill. It is required and throws an exception if not found.
Having both the notuser and user parameters is pretty redundant, but it's protection against a bad pattern for the user parm. I didn't want to put this script in the wild and have someone run it like
.\kill_processes.ps1 -computername domaincontroller -user "ser" -name "*" when trying to kill all of sergey's processes -- bye-bye domain controller is
NOT my goal.
param (
[string]$computername = "localhost",
[string]$notuser = "SERVICE|SYSTEM",
[string]$user = $(throw "enter the user name that started the process"),
[string]$name = $(throw "enter the process name to kill")
)
gwmi win32_process -computername $computername|
where {($_.getowner().User -notmatch $notuser) -and ($_.getowner().user -match $user) -and ($_.name -match $name)} |
foreach {$_.Terminate() >$null }