title: PowerShell: error checking in a while true loop?
body: <p>I have a <code>while($true)</code> loop with a <code>start-sleep -s 60</code> at the end of it. The purpose is to start an external PowerShell script <strong>as a different user</strong> which will run through a list of servers, check the event log for changes within the last minute and react accordingly. </p>
  
  <p>Since my while loop (below) is using the <code>-credential</code> flag to run the script as someone else, I'm concerned about errors (e.g. account locked out, expired password, missing file, etc). </p>
  
  <p>I tried an <code>if ($error)</code> statement, and changed the filename of the external script, but I was never alerted. I'm thinking it's because it never stops to re-check itself? </p>
  
  <pre><code>while($true) { 
  
      # Start the scan
      Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command &amp; c:\batch\02-Scan.ps1'
  
      # Sleep 60 seconds
      start-sleep -s 60
  
  }
  </code></pre>
  
  <p>I suppose I could change my scheduled task to run every minute, but so far this loop seems to have been working great. Just want to introduce error checking while the loop is active. </p>