Citation Ed Wilson 10th Review "10. Resolving Windows Powershell Errors in SQL Server Agent Jobs" from " 10 Tips for a SQL Server PowerShell Script :
10. Windows Powershell error handling in SQL Server Agent
By default, the ErrorActionPreference parameter is set to Continue, and this has consequences for how errors go to the SQL Server job server. If you run the Windows PowerShell command as a SQL Server agent job and there are no syntax errors yet, the command throws an error (for example, trying to get information about the operating system from an unavailable server). The SQL Server Agent job will report success. If you want the error condition to terminate the SQL Server Agent job or cause an error, you will need to add some error handling. You can configure the SQL Server Agent job during Windows PowerShell as follows:
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'

The task will succeed, but if you run it directly in Windows PowerShell, you will see:
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' get-wmiobject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA) At line:1 char:1 + get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
To create Windows PowerShell error bubbles for the SQL Server Agent, you must do one of the following:
but. Set $ ErrorActionPreference = "Stop"
$erroractionpreference = "Stop" get-wmiobject Win32_OperatingSystem -ComputerName 'nothere'
B. Set ErrorAction at the cmdlet level (more granular)
get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' -ErrorAction 'Stop'
C. Use Try / Catch with ErrorActionPreference or ErrorAction
try { get-wmiobject Win32_OperatingSystem -ComputerName 'nothere' -ErrorAction 'Stop' } catch { throw "Something went wrong" #or rethrow error #throw $_ #or throw an error no message #throw }
D. Continue and run SQL Server Agent
Say you have a collection of computers and you want to continue the error, but you also want to fail. In this case, you can use ErrorVariable:
#Note the -ErrorVariable parameter takes a variable name without the $ prefix. get-wmiobject Win32_OperatingSystem -ComputerName 'localhost','nothere','Win7boot' -ErrorVariable myError if ($myError) { throw ("$myError") }