jvcoach23
jvcoach23

Reputation: 3037

Run a batch file every x number of seconds using PowerShell

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.

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.

Upvotes: 8

Views: 14416

Answers (1)

Keith Hill
Keith Hill

Reputation: 201992

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

$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
}

Upvotes: 13

Related Questions