0

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
Rui Claro
  • 53
  • 5
  • Have you see [this](https://stackoverflow.com/questions/50200325/returning-an-exit-code-from-a-powershell-script/50200868) ? More specifically [this answer](https://stackoverflow.com/a/50202663/3641635). As you're using `-command`, PowerShell will not return you directly an exit code but only fail or success. – Zilog80 Jul 13 '21 at 12:27
  • Hi @zilog80. Powershell script is returning the proper exit code. – Rui Claro Jul 13 '21 at 13:32
  • IIRC PowerShell's `-File` parameter doesn't return the exit code correctly. Try replacing with a properly quoted `-Command` (or `-EncodedCommand`) as a workaround. – Bill_Stewart Jul 13 '21 at 14:16
  • @Bill_Stewart both with -File and -Command I get the same results – Rui Claro Jul 13 '21 at 14:34
  • The display of `exit 1` in your output is curious. The `exit` keyword should be treated as a statement here, not a [String] return value. It's the exact output ? – Zilog80 Jul 13 '21 at 14:47
  • @Zilog80 it's just something I've added to show that it exits with 1 – Rui Claro Jul 13 '21 at 16:26

1 Answers1

0

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

$returncode=Invoke-Command -Session $session -ScriptBlock { $lastexitcode }
Remove-PSSession $session
     
exit $returncode
Rui Claro
  • 53
  • 5