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

rom*_*man 4 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"
}
Run Code Online (Sandbox Code Playgroud)

Ans*_*ers 7

您正在那里运行外部命令,因此您需要检查自动变量 $LastExitCode以检测错误:

if ($LastExitCode -ne 0) {
  exit 1
}
Run Code Online (Sandbox Code Playgroud)

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

exit $LastExitCode
Run Code Online (Sandbox Code Playgroud)

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