如何在每隔30分钟后继续检查流程?每隔、流程、继续、分钟后

2023-09-04 01:39:56 作者:天天教你如何治脚麻

我需要kill the process如果开始时间是less than 2 hours. 如果开始时间是more than 2 hours.,我需要add sleep for 30 mins 我需要keep repeating它,直到进程不再运行。

到目前为止,我已经编写了以下脚本来执行上述操作。

$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)
           }   
        }
    }
}
如何将上述程序添加到do-while或另一个循环中,以保持检查,直到进程不再运行? 另外,如何实现4小时的最大定时器?

推荐答案

如果我理解正确的话,您的else条件可能使用do-while循环:

else {
    do {
        "$procName is still running, sleeping for 1800 sec"
        Start-Sleep -Seconds 1800
    } while(Get-Process | Where-Object Name -EQ $procName)
}
专题综合检测 二 30分钟 50分

但是,请注意,如果进程从未停止或您实现了最大计时器等,这可能会导致无限循环。

根据您关于实现最大计时器的评论,有许多方法可以做到这一点,我个人的偏好是使用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()
}