views:

45

answers:

1
+2  Q: 

powershell loop

I'd like to use a windows powershell 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. Windows Schedular i've used lot of times before for somethign similar, but for some reason schedular 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.

thanks shannon

+2  A: 

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
}
Keith Hill
great... thanks for the quick help.. works great
jvcoach23
Keith, why not only `while(1) { sleep -sec 45; .\script.ps1 }` ?
stej
That depends on whether the goal is to run literally ever `x` seconds (assuming here the batch file takes less than `x` seconds to execute) OR if it is to run say 20 seconds one time, sleep 25, run a second time and take 30 seconds and then sleep 25. Then the time period varies (45 - 55 seconds). If that doesn't matter, by all means simplify it to a simple sleep.
Keith Hill