Batch File help needed for PsList/PsKill when a process is over a specific age (elapsed time)

batchbatch-filekill

I'd like to request some help in creating a Batch file to run on a windows server which will monitor processes which sometimes get "stuck" and linger after they should be killed.

Specifcally, I can see the "age" of a process in the Elapsed Time column of the PsList command
http://technet.microsoft.com/en-us/sysinternals/bb896682.aspx

Name                Pid Pri Thd  Hnd   Priv        CPU Time    Elapsed Time
FMSCore            4908   8 146  892 750720     0:01:46.221     4:02:15.907
FMSCore            4780   8 144  943 853060     0:00:42.510     4:02:15.348
FMSCore            3532   8 146  878 553784     0:01:30.262     2:04:56.969
FMSCore            5384   8 147  753  45484     0:00:03.198     0:05:11.267
FMSCore            9548   8 133  608  17408     0:00:00.592     0:00:34.298

The next step, is I only want to kill processes which are older than 4 hours. So I believe we will need to parse the results of my PsList command, extract the last column, parse for hours, and if we find that it's "old enough" we parse out it's PID and kill it.

If we were talking about bash or some other scripting language I think I could figure it out, but for a batch script, I don't know.

recommendations?

(note: I'd be willing to run an autoit script or something else, if needed)

Best Answer

You probably want PowerShell in this case. Date and time manipulation in batch files is kinda hard (you can't even reliably get the current date/time, for example), comparing arbitrary data types as well.

In PowerShell this is trivial:

Get-Process | where { $_.StartTime -lt (Get-Date).AddHours(-4) } | Stop-Process

ETA: After a little more thought this may be easy enough in a batch file, I'll look into it later today and see whether I can get something working.

Related Topic