Share via

Catch exitcode from EXE

Marcus Östman 21 Reputation points
2020-09-05T09:43:39.89+00:00

Hi,
I'm trying to catch errorlevel/exitcode from a executable, both return 0. I don't understand why.

The folder "d:\Temp\exists\" exists.

$rar="c:\Program Files\WinRAR\Rar.exe"
$archive1="TMP.rar"
$argList = @("a", ('"'+$archive1+'"'), ("d:\Temp\exists\"))
Start-Process -FilePath $rar -ArgumentList $argList -Wait #-NoNewWindow
$LASTEXITCODE

The folder "d:\Temp\exists\" does NOT exists.

$rar="c:\Program Files\WinRAR\Rar.exe"
$archive1="TMP.rar"
$argList = @("a", ('"'+$archive1+'"'), ("d:\Temp\doesNOTexists\"))
Start-Process -FilePath $rar -ArgumentList $argList -Wait #-NoNewWindow
$LASTEXITCODE

Windows for business | Windows Server | User experience | PowerShell

Answer accepted by question author

  1. Rich Matheisen 48,116 Reputation points
    2020-09-05T14:31:23.587+00:00

    While you used the "-Wait" switch you haven't used the "-Passthru" switch and you haven't kept the process object returned by the Start-Process cmdlet. See this link: obtaining-exitcode-using-start-process-and-waitforexit-instead-of-wait

    When the process ends, check the "ExitCode" property of the process object.

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Marcus Östman 21 Reputation points
    2020-09-07T19:31:53.057+00:00

    Thanks for the input.
    After some inspiration from the link you provided I went for this solution.

    function rar_update([String] $archive1, [String] $list1, $varName) {
    & "c:\Program Files\WinRAR\Rar.exe" a "$archive1" "$list1"
    Set-Variable -Name $varName -Value $LASTEXITCODE -Scope Global
    }

    rar_update "Path/Backup.rar" "@mutia keyza /Backup.lst" "r_error1"
    if (($r_error1 -ne 0) ... #if not 0 handle it as an error


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.