roman
roman

Reputation: 667

How to return error code 1 on error from PowerShell?

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"
}

Upvotes: 8

Views: 35922

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

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.

Upvotes: 12

Related Questions