Search code examples
powershellerror-handlingpowershell-3.0powershell-remotingerror-code

Powershell : How to check the good execution of a batch file on a remote computer using invoke-command


here is the relevant code :

$op=invoke-command -computername test -scriptblock{
        & "cmd.exe" /c c:\temp\psbatch.bat 2>&1 
        $LASTEXITCODE 
    }
if ($op - eq 0) {echo "success"}
else {echo "failure"}

The problem is that if my batch echo something, the output will be capture in $op so it will not be equal to 0.

How to handle that ?


Solution

  • You can try something like this:

    $op=invoke-command -computername test -scriptblock{
        & "cmd.exe" /c c:\temp\psbatch.bat 2>&1 
        $LASTEXITCODE 
    }
    if (@($op)[-1] -eq 0) {echo "success"}
    else {echo "failure"}
    

    Force the result to an array, and then test just the last line, which will be the last exit code. Anything echoed before that will be ignored.