How to get the error code or return code of an .exe

Hi guys, I was trying to create a script for backing up the print environment.
In the script, I call printbrm.exe, which might work flawless, or might return an error code.
I would like to do some action (like sending an email) when an error code appears.
My line in Powershell looks like this:
C:\Windows\System32\spool\tools\printbrm.exe -B -S <myprintserver> -F D:&lt;myprintserver>.export

This line calls the printbrm executable and adds the parameters -B (for backup), -S (for specifying the server) and -F (for specifying the export file).
If the backup works fine, printbrm.exe throws a result in the console “Successfully finished operation”.
If the export file is already existing, printbrm.exe returns “The following error occurred: 0x80070050. The file exists.”

Now, I would like to do an action, if there is any error code.
How can I catch this one? I read about the “$?” variable and “$Lastexitcode”, but they always return 0 or $true respectively.

Thank you in advance!

$LASTEXITCODE is set to the return code from the executable. If it’s 0 even when an error occurred, then that’s just how that particular executable was written (which makes it a real pain to use in a script.)

On top of that, it looks like it writes all if this information (including errors) to stdout, so you’re left with few options. If you need to use this executable instead of a more script-friendly alternative, you’d have to parse the output yourself. For example:

$output = C:\Windows\System32\spool\tools\printbrm.exe -B -S <myprintserver> -F D:\<myprintserver>.export

# $output will be an array of strings, at this point, one per line of output.

if ($output -match 'The following error occurred')
    # An error occurred, take action

Thank you very much Dave. Such simple ideas make us get a huge step closer to what we want to achieve.
My respects to you and all of you guys, who make our goals achievable!