0

suppose i have 2 servers. lets say i am performing an operation on these 2 servers sequentially (for loop) and i pass an exit code in 3 scenarios:

2 servers success: exit 0
2 servers fail: exit 1
1 server fail 1 server success: exit 0

currently, i use this exit 1 to return an exit code to AutoSys (where we have automated jobs) to indicate failure if something fails, and exit 0 to indicate success.

however, this exits the script as well, so wherever i have this command the script would stop executing.

this is fine in the current 3 scenarios i have, however, we would like to change the last scenario 1 server fail 1 server success: exit 0 to 1 server fail 1 server success: exit 1 in which if one server fails, even if the other server succeeds, send failure code.

this may work generally if the first server succeeds and the 2nd one fails because that is the end of the script anyways so its fine to exit. but in the case where the FIRST server fails but there is YET another server to run the operation on, it will exit without letting the operation to run on server2.

so i need a way to exit 1 (fail) WITHOUT ending the script operation

6
  • Can you just store the value in a variable and exit at the end of the script? Commented May 17, 2019 at 19:27
  • @RyanBemrose i dont think so...but let me try Commented May 17, 2019 at 19:28
  • @RyanBemrose just tried it. it doesnt work. wherever exit is it will immediately exit, regardless if you set it to a variable Commented May 17, 2019 at 19:33
  • I would say to replace the Exit 1 section of both servers to something like $Server1Failed = $true and $Server2Failed = $true. Then, at the end of the script, have an if statement like this `if ($Server1Failed -or $Server2Failed) {Exit 1} else {Exit 0}. Commented May 17, 2019 at 20:20
  • @kuzimoto looks like ill have to change the structure of my script....ahhhh i hoped thered be another easy alternative Commented May 17, 2019 at 20:28

1 Answer 1

1

I do things like this in .bat files. You can tell by the exit number which job had an error. It's kind of like setting bits in an integer.

$err = 0

# 1st job
if (-not $?) { $err += 1 }

# 2nd job
if (-not $?) { $err += 2 }

# 3rd job
if (-not $?) { $err += 4 }

exit $err

Maybe you can do something with $error, but it contains the errors of all scripts run within a powershell process.

Here's another method I've recently been using. You can't tell which command made the error, but you can tell how many errors there are in the whole script.

$errorcount = $Error.Count

Get-Childitem foo1
Get-Childitem foo2
Get-Childitem foo3

exit $Error.Count - $errorcount

Then if all 3 didn't exist, $LASTEXITCODE would be 3. Or %errorlevel%.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.