Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return error code 1 on error from PowerShell?

Tags:

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"
}
like image 670
roman Avatar asked Mar 11 '23 03:03

roman


1 Answers

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.

like image 159
Ansgar Wiechers Avatar answered Mar 20 '23 15:03

Ansgar Wiechers