windows 使用 PowerShell 每 x 秒运行一个批处理文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2426993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:06:24  来源:igfitidea点击:

Run a batch file every x number of seconds using PowerShell

windowspowershell

提问by jvcoach23

I'd like to use a windows PowerShell script to run a batch file every x number of seconds. So it's the same batch file being run over and over again.

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

I've done some looking, but can't find what I'm looking for. It's for something that I want to run on a Windows XP machine. I've used Windows Scheduler a lot of times before for something similar, but for some reason Windows Scheduler only runs once... Then no more. I also don't want to have the batch file call itself, because it will error out after it runs so many times.

我做了一些寻找,但找不到我要找的东西。这是我想在 Windows XP 机器上运行的东西。我以前曾多次使用 Windows Scheduler 进行类似的操作,但出于某种原因,Windows Scheduler 只运行一次......然后就没有了。我也不想让批处理文件自己调用,因为它运行了很多次后会出错。

回答by Keith Hill

Just put the call to the batch file in a while loop e.g.:

只需在 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
}