使用PowerShell每隔x秒运行批处理文件

jvc*_*h23 7 windows powershell

我想使用Windows PowerShell脚本每隔x秒运行批处理文件.所以这是一遍又一遍地运行的同一个批处理文件.

我做了一些看,但找不到我想要的东西.这是我希望在Windows XP机器上运行的东西.我曾经多次使用过Windows Scheduler来做类似的事情,但出于某种原因,Windows Scheduler只运行一次......然后就没有了.我也不想让批处理文件本身调用,因为它会在运行很多次后出错.

Kei*_*ill 13

只需在while循环中调用批处理文件,例如:

$period = [timespan]::FromSeconds(45)
$lastRunTime = [DateTime]::MinValue 
while (1)
{
    # If the next period isn't here yet, sleep so we don't consume CPU
    while ((Get-Date) - $lastRunTime -lt $period) { 
        Start-Sleep -Milliseconds 500
    }
    $lastRunTime = Get-Date
    # Call your batch file here
}
Run Code Online (Sandbox Code Playgroud)

  • 基思,为什么不只是`while(1){sleep -sec 45; .\ script.ps1}`? (5认同)
  • 这取决于目标是否始终以"x"秒运行(假设此处批处理文件执行时间小于"x"秒)或者如果要运行一次20秒,则睡眠25次,再次运行并且需要30秒然后再睡25个.然后时间段变化(45-55秒).如果这无关紧要,请务必将其简化为简单的睡眠. (3认同)