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
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.
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
}