0

I have an application that when opened sometimes opens several times. The application has one Process and background process but sometimes many can open.

I am trying to write a powershell script that launches the application and checks to see if it opened multiple and kills the processes that should not be there.

Start-Process -Filepath "path"
Get-Process -Name name* | Where-Object {$_.Id -ne $pid} | stop-process

This is the bit I have now but this closes all instances of the file name.

How can I just close the places where there are multiple instance.

Also, I can't hardcode a PID because it changes everytime it opens..

Thanks

1
  • I personally think this is an XY problem - Link, I think we need to understand why the application opens multiple times, is this software publicly available or software you have written yourself?, how is the software executed?
    – CraftyB
    Aug 17, 2020 at 8:47

2 Answers 2

0

What you want to do here is get the ID immediately when starting your app, then close everything that does not match.

$id = (Start-Process notepad -passthru).ID
Get-Process -Name notepad* | Where-Object {$_.Id -ne $id} | stop-process

Above I have sampled with notepad, but you can change to your process name. You can test by opening multiple notepads first, then running this. Only the one you started will remain.

4
  • This is not going to work by reasoning of how the user would perform tasks. If the user starts the process without launching this powershell script, and you run this, all of his programs are closed and this new instance is launched in its place. It also means the user has to run the script, and if they don't, then nothing happens. If the user launches this script multiple times by accident, it will have different id's and one script may terminate the process of the other script while the other script terminates the process of the first.
    – LPChip
    Aug 10, 2020 at 17:48
  • Also, if the program itself spawns these additional processes, they may be required for the program. Think as Chrome having a process for every tab, every extension, etc... Killing the wrong sub-tab will essentially crash chrome, closing it entirely, making it seems like chrome itself was closed.
    – LPChip
    Aug 10, 2020 at 17:49
  • Is there a way I can do this while capturing two PID's? This said application has a background process and the application itself for a total of 2. This solution you have would just capture the background process and close the actual application. Thanks!
    – JasonL7
    Aug 10, 2020 at 17:49
  • @LPChip ah, you're right. I was thinking he was launching this with a script.
    – Narzard
    Aug 10, 2020 at 17:56
0

Killing all processes of given executable in PowerShell is done with one of:

Get–Process "notepad" | Stop–Process
Stop-Process -name explorer

You may also use the taskkill utility.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .