GMTpilot
GMTpilot

Reputation: 21

How to kill the longest running instance of a process

Let me preface this by saying yesterday was the first time I saw Powershell.

I'm trying to create a script that will kill the process "pptview" based on how long its been running. Specifically, I can have several instances of pptview running at the same time but I only want to kill the one that has been running the longest.

So far I have created a script that searches if duplicate instances of the process exist. If it doesn't find any it goes to sleep for 60 seconds then checks again.

I'm using taskkill to kill the process via the PID - which works well.

The bit I'm stuck on is how to determine which is the longest running instance and how to get the PID so I can feed it back to taskkill.

Upvotes: 2

Views: 1144

Answers (1)

user4003407
user4003407

Reputation: 22122

You does not have to use taskkill to kill process. You can use Stop-Process PowerShell cmdlet instead. To find the longest running process, you can sort processes by StartTime and select the first:

Get-Process pptview|
Sort-Object StartTime|
Select-Object -First 1|
Stop-Process

But something says me, that you want to stop all but the youngest one:

Get-Process pptview|
Sort-Object StartTime -Descending|
Select-Object -Skip 1|
Stop-Process

Upvotes: 2

Related Questions