'How to keep checking the process after every 30 minutes?

I need to kill the process if start time is less than 2 hours. I need to add sleep for 30 mins if start time is more than 2 hours. I need to keep repeating it until the process is no more running.

I have written the below script so far to perform the above action.

$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)) {
                Stop-Process $_ -Force
            }
        else {
               sleep(1800)
           }   
        }
    }
}

How to add the above program in a do-while or another loop so as to keep checking until the process is no more running? Also, how to implement a maximum timer of 4 hours?



Solution 1:[1]

If I understood correctly, your else condition could look like this using a do-while loop:

else {
    do {
        "$procName is still running, sleeping for 1800 sec"
        Start-Sleep -Seconds 1800
    } while(Get-Process | Where-Object Name -EQ $procName)
}

However note that this could cause an infinite loop if the process never stops or you implement a maximum timer, etc.


Following your comment regarding implementing a maximum timer, there are many ways you could do it, my personal preference would be to use a StopWatch:

else {
    $timer = [System.Diagnostics.Stopwatch]::StartNew()
    do {
        # Do this while the process is still running AND
        # the timer hasn't yet reached 4 hours
        "$procName is still running, sleeping for 1800 sec"
        Start-Sleep -Seconds 1800
        $stillRunning = Get-Process | Where-Object Name -EQ $procName
    } while($stillRunning -and $timer.Elapsed.Hours -lt 4)
    $timer.Stop()
}

Solution 2:[2]

I suggest you use a windows schedule task that launch your powershell script every 30 minutes or so instead of blocking resource with your powershell that is waiting.

You can launch powershell and pass a script. PowerShell.exe -File "C:\script.ps1"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 jboo