0

I have a remote access program that does not clean up after itself after it is closed. In Task Manager, I oftentimes find 5 to 10 instances of the program running. For instance:

  • XYZ.exe
  • XYZ.exe
  • XYZ.exe
  • XYZ.exe
  • XYZ.exe

I have a simple Powershell script to stop these processes, but the problem is I want to close n-1 out of n processes.

> Stop-Process -Force -Name XYZ*

kills n out of n processes.

Is there a way to kill all processes of a program while leaving open the newest (e.g. XYZ.exe #5)?

cmac
  • 1
  • 2
  • Use ' Get-Process -name firefox | sort ID' to list them ordered by ID. Then you need to enumerate them and delete all apart the last one. And then add an '| Stop-Process' at the end – Francesco Mantovani Mar 20 '20 at 20:38

2 Answers2

2

Use Get-Process to discover all matching processes ahead of time, then simply remove one of them before killing the rest:

Get-Process -Name XYZ* |Select -Skip 1 |Stop-Process -Force
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
0

Try this: it closes all non responding processes

Get-Process -name XYZ.exe| Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process
Francesco Mantovani
  • 10,216
  • 13
  • 73
  • 113