Powershell Task Error Handling

How do folks handle errors inside a PowerShell Task. It seems like the task will *always* succeed.

Things I've tried.

1. throw

2. $PSCmdlet.ThrowTerminatingError

3. $ErrorActionPreference = 'Stop'

4. Write-Error

The only thing I can think to do is set up a Script Task to inspect the Results variable. The problem there is that the output is PSDataCollection<PSObject> and a Script task doesn't natively support the System.Management.Automation library. One would have to manually add the dll.

So the task appears to be worth *ALOT* less than originally thought.

  • Here are a few methods you can try:

    1. Using -ErrorAction Stop: This is a common way to handle errors in PowerShell. You can use this parameter with any cmdlet that supports common parameters. If a cmdlet encounters an error, this parameter will force the cmdlet to stop executing and return an error.

    2. Using throw statement: The throw keyword in PowerShell can be used to create a terminating error. However, you need to make sure that the error is not caught in a try/catch block within the script. If it is, the error will be handled, and the script will continue to run.

    3. Using exit statement: You can use the exit statement to stop the execution of the script and return a specific exit code. If you return a non-zero exit code, the task will fail.

    4. Using Set-Variable -Name "LASTEXITCODE" -Value 1 -Scope Global: This is another way to set a non-zero exit code and make the task fail.

    Remember, the key is to generate a terminating error or a non-zero exit code. If the error is non-terminating, the script will continue to run and the task will succeed.

    As for the issue with the PSDataCollection<PSObject>, you're correct that a Script Task doesn't natively support the System.Management.Automation library. You would need to manually add the DLL. However, you could also consider converting the PSDataCollection<PSObject> to a more manageable format within the PowerShell script itself before returning it to the Script Task.

  • It is all a moot point now because I can't even get Import-Module ActiveDirectory to work in the IS Server context.

Reply Children
No Data