How to fail sql server agent job if powershell script fails
Problem 1
I tried adding a powershell script to a sql server agent job step, but there are some severe limitations where write-host or write-verbose outputs are not allowed instead of ignored, which should make sens. Then the job crashes with the following error:A job step received an error at line [xx] in a PowerShell script. The corresponding line is 'write-host "test"; '. Correct the script and reschedule the job. The error information returned by PowerShell is: 'A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows. '. Process Exit Code -1. The step failed.
Problem 2
So instead I created a Operating System (CmdExec) step with calling powershell.exe, but it never fails, no matter how bad powershell i write. Just gives false positivies by not detecting step failure. Errors are visibile in the history though.The following will not fail agent job when powershell script fails
powershell -file "d:\scripts\FailingScript.ps1" -parameter1 value1 -parameter2 value2
Solution
Change the call to -command like below, this will fail correctly if powershell script failspowershell -command "try { & 'd:\scripts\FailingScript.ps1' -parameter1 value1 -parameter2 value2 } catch { throw $_ }"
Comments