【问题标题】:Can I return an exit code %errorlevel% from WSL Bash to Powershell or Command Prompt?我可以将退出代码 %errorlevel% 从 WSL Bash 返回到 Powershell 或命令提示符吗?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2016-12-12
    • 2012-07-05
    相关资源
    最近更新 更多