Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 239
jvcoach23 Avatar asked Mar 11 '10 16:03

jvcoach23


People also ask

How do I loop a batch script only a certain amount of times?

There is an example: @echo off set loop=0 :loop echo hello world set /a loop=%loop%+1 if "%loop%"=="2" goto next goto loop :next echo This text will appear after repeating "hello world" for 2 times. Output: hello world hello world This text will appear after repeating "hello world" for 2 times.

How do I schedule a batch file to run automatically?

Schedule Batch Files With Windows Task SchedulerStart the process by opening your Microsoft Windows PC's Start menu, searching for Task Scheduler, and selecting that tool in the search results. Select Action > Create Basic Task on the Task Scheduler's window. You'll use this task to run your batch file.

How do I run a batch file in PowerShell?

To run the batch commands from PowerShell, we can use the Start-Process cmdlet as earlier explained and which executes a cmd command on the server.


1 Answers

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
}
like image 157
Keith Hill Avatar answered Sep 20 '22 14:09

Keith Hill