我可以从 WSL Bash 返回退出代码 %errorlevel% 到 Powershell 或命令提示符吗?

问题描述 投票:0回答:2

我有一个 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
bash powershell exit-code
2个回答
0
投票

解决了。 刚刚改了$?到 $lastexitcode 并返回该变量

$returncode=Invoke-Command -Session $session -ScriptBlock { $lastexitcode }
Remove-PSSession $session
     
exit $returncode

0
投票

一个更简单的例子是:

Invoke-Expression -Command 'bash script.sh'
$success = Invoke-Expression -Command '$lastexitcode'
Write-Host $success
© www.soinside.com 2019 - 2024. All rights reserved.