8

Can you give an example how to return error code 1 on error using PowerShell?

For example handling this situation:

if ($serviceUserName) {
  cmd /c $serviceBinaryFinalPath install -username:$serviceUserName -password:$serviceUserPassword -servicename:"$ServiceName" -displayname:"$serviceDisplayName" -description:"$serviceDescription"
} else {
  cmd /c $serviceBinaryFinalPath install --localsystem -servicename:"$ServiceName" -displayname:"$serviceDisplayName" -description:"$serviceDescription"
}
2
  • 1
    try {bla-bla-bla} catch {exit 1} Commented Jan 17, 2017 at 14:51
  • Why cmd /c? You don't need it. Commented Jan 17, 2017 at 17:54

1 Answer 1

12

You're running external commands there, so you need to check the automatic variable $LastExitCode for detecting errors:

if ($LastExitCode -ne 0) {
  exit 1
}

Or just exit with the exit code of the last external command:

exit $LastExitCode

Note that some external commands (robocopy for instance) use exit codes not only for signaling errors, but also for providing non-error status information.

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

1 Comment

oh, I didn't even notice he isn't using powershell command :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.