【发布时间】:2021-07-13 11:54:37
【问题描述】:
我有一个 bash 脚本,它根据条件返回出口 0 或出口 1。该 bash 脚本是从执行远程处理的 Windows Powershell 调用的。我在命令提示符下测试了 %errorlevel%,但它没有返回正确的值!
远程执行.ps1
param (
[Parameter(Mandatory=$true,HelpMessage="Remote computer")]
[String]$computer,
[Parameter(Mandatory=$true,HelpMessage="Command to be executed on the remote computer")]
[String]$command,
)
$message = "Executing: '" + $command + "' on remote computer " + $computer
Write-Host $message
$session = New-PSSession -ComputerName $computer
Invoke-Command -Session $session -ScriptBlock ([scriptblock]::Create($command))
$returncode=Invoke-Command -Session $session -ScriptBlock { $? }
Remove-PSSession $session
if ($returncode -eq $true) {
return 0
exit 0
}
else {
return 1
exit 1
}
}
powershell -file RemoteExecute.ps1 -computer "myServer" -command "bash -c './somescript.sh'"
Executing: bash -c './somescript.sh' on remote computer myServer
ERROR. Aborted!
exit 1
C:\Windows\system32>echo %errorlevel%
0
【问题讨论】:
-
你看到this了吗?更具体地说this answer。当您使用
-command时,PowerShell 不会直接向您返回退出代码,而只会返回失败或成功。 -
嗨@zilog80。 Powershell 脚本正在返回正确的退出代码。
-
IIRC PowerShell 的
-File参数未正确返回退出代码。尝试用正确引用的-Command(或-EncodedCommand)替换作为解决方法。 -
@Bill_Stewart 使用 -File 和 -Command 我得到相同的结果
-
exit 1在您的输出中的显示很奇怪。exit关键字在这里应被视为语句,而不是 [String] 返回值。这是确切的输出?
标签: bash powershell exit-code