For Try / Catch to work, PowerShell needs a final exception. When you run the cmdlet in the Try block, you can do this using -erroraction Stop (or use the -ea alias). As you already understand, SCHTASKS.EXE cannot do this. Without a final exception, the code in the Catch block will never run.
What you need to do is go out of the box, so to speak, and independently check if Schtasks has worked. If so, you can use Write-Error in your Try block.
One thing you can try is to use the Start-Process and see the exit code. Any error other than 0 must be an error.
Try { get-date $p=Start-Process schtasks.exe -ArgumentList "/Create foo" -wait -passthru if ($p.exitcode -ne 0) { write-error "I failed with error $($p.exitcode)" } } Catch { "oops" $_.Exception }
source share