Pausing Long-Running PowerShell

I recently developed a PowerShell script that was going to run for a few days.

Given it was going to run for so long, I really wanted to be able to pause it if necessary to prevent having to start all over again. Not only that, but ideally I wanted others to be able to pause it too.

The script was running in bite-size batches so my initial thinking was to add a Start-Sleep at the start of each batch and look for keyboard input. However, this only works if it is running as a service account so others can log in to access the script window.

I decided to combine this concept with checking the content of a text file. If it contains YES then just carry on as usual, otherwise, sleep and then check again.

This means that anybody can edit the text file, change the contents and save it – and the script will gracefully pause when it gets to the next convenient point.

To start it up again then anybody with access can just edit the text file, set the value to YES, and the script will start up again as if nothing happened when it gets to the end of the current sleep.

$batchNum = 1;
$continueFile = 'continue.txt';
Write-Host "Starting . . .";
do {
  Write-Host "Batch $batchNum";
  do {
    $continue = Get-Content $continueFile;
    if ($continue -ne 'YES') {
      Write-Host "Pausing for 10 seconds - to restart ensure continue.txt = YES";
      Start-Sleep 10;
    } else {
      Write-Host "Continuing . . .";
    }
  } while ($continue -ne 'YES')
  Start-Sleep 10;
  $batchNum++;
} while ($batchNum -lt 1000)
Write-Host "Finished . . .";

Of course, if you really need to then you can always CTRL+C to cancel the script at any stage too, but this is a simple way to not only allow the script owner to pause but allow others to pause too.

This entry was posted in PowerShell and tagged , , , , , , . Bookmark the permalink.

Leave a comment