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
6
  • Have you see this ? More specifically this answer. As you're using -command, PowerShell will not return you directly an exit code but only fail or success. Commented Jul 13, 2021 at 12:27
  • Hi @zilog80. Powershell script is returning the proper exit code. Commented Jul 13, 2021 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. Commented Jul 13, 2021 at 14:16
  • @Bill_Stewart both with -File and -Command I get the same results Commented Jul 13, 2021 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 ? Commented Jul 13, 2021 at 14:47

2 Answers 2

0

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

$returncode=Invoke-Command -Session $session -ScriptBlock { $lastexitcode }
Remove-PSSession $session
     
exit $returncode
Sign up to request clarification or add additional context in comments.

Comments

0

A more simple example would be:

Invoke-Expression -Command 'bash script.sh'
$success = Invoke-Expression -Command '$lastexitcode'
Write-Host $success

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.