如何从PowerShell出错时返回错误代码1?

时间:2017-01-17 14:44:31

标签: powershell

您能举例说明如何使用PowerShell在错误时返回错误代码1吗?

例如处理这种情况:

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

1 个答案:

答案 0 :(得分:4)

您在那里运行外部命令,因此您需要检查automatic variable $LastExitCode以检测错误:

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

或者只使用最后一个外部命令的退出代码退出:

exit $LastExitCode

请注意,某些外部命令(例如robocopy)不仅使用退出代码来发送信号错误,还使用退出代码来提供非错误状态信息。