我有一个 bash 脚本,根据条件返回 exit 0 或 exit 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 -文件 RemoteExecute.ps1 -计算机“myServer”-命令“bash -c './somescript.sh'”
Executing: bash -c './somescript.sh' on remote computer myServer
ERROR. Aborted!
exit 1
C:\Windows\system32>echo %errorlevel%
0
解决了。 刚刚改了$?到 $lastexitcode 并返回该变量
$returncode=Invoke-Command -Session $session -ScriptBlock { $lastexitcode }
Remove-PSSession $session
exit $returncode
一个更简单的例子是:
Invoke-Expression -Command 'bash script.sh'
$success = Invoke-Expression -Command '$lastexitcode'
Write-Host $success