try-catch-fail with powershell and schtasks

Question:

I’m new to powershell, but I’m trying to output some simple logging in a ps I’m writing to create scheduled tasks. My code is below. It seems that it doesn’t throw an exception when you get an error with schtasks. Another SO question mentioned this with fileIO actions and suggested doing “-ea stop” but that doesn’t work with schtasks.

I verified that ‘Add-Content -path “\servername!incoming\Deploy\log.txt” -value “test”‘works, so like I said I’m fairly sure it’s just not throwing an exception.

Answer:

In order for a Try/Catch to work, PowerShell needs a terminating exception. When running a cmdlet in a Try block you can make that happen by using -erroraction Stop (or use the -ea alias). As you already realize SCHTASKS.EXE can’t do this. Without a terminating exception, the code in the Catch block will never run.

What you have to do is step out side the box, so to speak, and independently check if Schtasks failed. If so, they you can use Write-Error in your Try block.

One thing you might try is using Start-Process and look at the exit code. Anything other than 0 should be an error.

Source:

try-catch-fail with powershell and schtasks by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply