Stopping Every Instance of PowerShell.exe (except the one I'm in)

PowerShell Team

Our Test Architect just dropped by my office and pitched me a PowerShell question with a nice, quick answer.

He wanted to stop every process of a particular name, except for the instance that was running the script.

You can do this in one nice pipeline:

Get-Process Powershell  | Where-Object { $_.ID -ne $pid } | Stop-Process

Get-Process takes a positional parameter (name), which is a wildcard that supplies the name of the process.  It returns back a bunch of ProcessInfo objects, which have a property, ID (the process ID).  $pid is a variable that will tell you the current process ID in PowerShell.  Where-Object { $_.ID -ne $pid } simply returns every instance that isn’t the current instance.  Stop-Process takes ProcessInfo from objects, and will stop the processes that were piped into it (which is now every instance of PowerShell except the one I’m in).

Another day, another PowerShell question answered.

Hope this Helps,

James Brundage [MSFT]


Discussion is closed.

Feedback usabilla icon