Pat
Pat

Reputation: 1203

PowerShell: error checking in a while true loop?

I have a while($true) loop with a start-sleep -s 60 at the end of it. The purpose is to start an external PowerShell script as a different user which will run through a list of servers, check the event log for changes within the last minute and react accordingly.

Since my while loop (below) is using the -credential flag to run the script as someone else, I'm concerned about errors (e.g. account locked out, expired password, missing file, etc).

I tried an if ($error) 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?

while($true) { 

    # Start the scan
    Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command & c:\batch\02-Scan.ps1'

    # Sleep 60 seconds
    start-sleep -s 60

}

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.

Upvotes: 3

Views: 16355

Answers (2)

Frode F.
Frode F.

Reputation: 54821

Have you tried try/catch blocks? Wrong credentials is a terminating error, so the rest of the code in the try block won't run after a credentials-error. When you catch it, you can do whatever you want.. Ex.

try { 
    Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command & c:\batch\02-Scan.ps1'
} catch {
    #Catches terminating exceptions and display it's message
    Write-Error $_.message
}

If you want to catch all errors, add -ErrorAction Stopto the Start-Processline. As said, credentials should be a terminating error, which make the erroraction parameter unnecessary

EDIT Why would you use Start-Process to run a script in the first place? I switched it to Invoke-Command which runs a powershell script remotely. When the scriptfile is missing, you will recieve a NON-terminating error. Because it's a non-terminating error, we need to use the -ErrorAction Stop parameter. To catch the missing-file error and every other error(like credentials), use something like this:

try { Invoke-Command -ScriptBlock { & c:\batch\02-Scan.ps1 } -ErrorAction Stop
} catch {
    if ($_.Exception.GetType().Name -eq "CommandNotFoundException") {
        Write-Error "File is missing"
    } else {
        Write-Error "Something went wrong. Errormessage: $_"
        #or throw it directly:
        #throw $_
    }
}

Upvotes: 3

mjolinor
mjolinor

Reputation: 68243

Maybe?

while($true) { 

# Start the scan
try{
Start-Process powershell -Credential $credentials -ArgumentList '-noprofile -command & c:\batch\02-Scan.ps1' -ErrorAction Stop
}
  catch {
          send-alert
          break
          }

# Sleep 60 seconds
start-sleep -s 60
}

Upvotes: 0

Related Questions