Question

I have a script (webdeploy.ps1) that runs fine locally or remotely via invoke-command. For one reason or another, webdeploy.ps1 will fail and exit before reaching the end of the script due to some catastrophic error that can't be handled by webdeploy.ps1 (ie. out of disk space). The script terminates after a Write-Error documenting the error. End user is notified. All is good.

Now when webdeploy.ps1 is executed remotely by Invoke-Command -asjob, the job state always return "Completed" even though the script failed. Are there any ways to set the job state as failed such that when I run get-job I can immediately see which server failed / completed successfully.

foreach ($webserver in $webServers)
{
    Invoke-Command -ComputerName $webServer -FilePath .\webdeploy.ps1 -AsJob -JobName "WebDeploy"
}



get-job | select name, id, State, Location | Format-Table -AutoSize

Name       Id State     Location               
----       -- -----     --------               
WebDeploy 102 Completed dev-web1
WebDeploy 104 Completed dev-web2
Was it helpful?

Solution

Write-Error only writes non-terminating errors, I believe, so perhaps the job is sensing that there's an error, but not necessarily a terminating error.

You might want to try either using throw instead of Write-Error, or explicitly exiting with a nonzero return code (though I'm not sure the latter actually makes much of a difference when it comes to reporting of the job state).

For a deeper understanding of terminating and non-terminating errors, and when to use Write-Error vs. throw, check out this thread.

OTHER TIPS

You can use the throw command in your webdploy.ps1 to set the job state as failed.

Example:

PS F:\> Start-Job -ScriptBlock { throw "error" }

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
5               Job5            Running    True            localhost             throw "error"


PS F:\> Get-Job

Id              Name            State      HasMoreData     Location             Command
--              ----            -----      -----------     --------             -------
5               Job5            Failed     False           localhost             throw "error"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top