Home > Net >  Kill the process if start time is less than 2 hours
Kill the process if start time is less than 2 hours

Time:03-09

I need to kill the process if start time is less than 2 hours.

I have written the below cmdlet to find out the starttime but how to find out if is it less than 2 hours:

get-process process1 | select starttime

There is also a possibility that on some hosts process1 is not running. so I need to check first if the process1 is running

CodePudding user response:

You can use a loop of your choice, in this example ForEach-Object in addition to an if condition to check if the StartTime value is lower than 2 hours.

If you need to check first is the process is running then you would need to get all processes and filter by the process name you're looking for. Then check if the returned value from Where-Object is $null or not.

$procName = 'myprocess'
$process = Get-Process | Where-Object Name -EQ $procName
if(-not $process) {
    Write-Warning "$procName not found!"
}
else {
    $process | ForEach-Object {
        if($_.StartTime -lt [datetime]::Now.AddHours(-2)) {
            try {
                'Attempting to stop {0}' -f $_.Name
                Stop-Process $_ -Force
                '{0} successfully stopped.' -f $_.Name
            }
            catch {
                Write-Warning $_.Exception.Message
            }
        }
    }
}
  • Related