Search code examples
bashpowershellexit-code

Can I return an exit code %errorlevel% from WSL Bash to Powershell or Command Prompt?


I have a bash script that returns exit 0 or exit 1 depending on conditions. That bash script is called from a Windows Powershell that does remoting. I test the %errorlevel% in the command prompt but it does not return the proper value!

remoteexecute.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

Solution

  • Solved. Just changed the $? to $lastexitcode and returned that variable

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