Question

I would like to see if I could get some help on an error code. My final script will be to set an SMTP address for a mailbox, but I just used this code below as an example.

Set-Mailbox jsmith -AntispamBypassEnabled $false
    if ($LastExitCode -eq 1)
    {
    echo "Exit Code 1" $lastexitcode
    }
    else
    {
    echo "Exit Code 0" $lastexitcode
    }

My expectation is that the first time I run the command, it does the work and I get successful error code. The second time I run the command, powershell comes back with the following.

Warning: The command completed successfully but no settings have been modified.

I want to be able to get an error code for 3 situations. (It worked, It failed, and then the one above that it worked, but that no changes were made.) I just can't seem to find any examples of this and would really appreciate some suggestions.

Thanks.

Michael

Ok, I got a great response and now I am using the following code. I have to modify thousands of objects and they will all be at different error codes, so I need to be able to write any of the conditions to a log file. I have a bunch of environment variables throughout the script, so in the end, I am going to put a "User Passed/Failed" $EmailAddress $DisplayName etc.....

Try { Set-Mailbox jsmith -AntispamBypassEnabled $false -ErrorAction Stop -   WarningVariable Warn }

Catch { Exit 2 } Write-Host "Exit Code 2"

if ($Warn) { Exit 1 } Write-Host "Exit Code 1"

else       { Exit 0 } Write-Host "Exit Code 0"
Was it helpful?

Solution 2

Try this. It should exit with 0 if successful, 1 if successful but no changes, and 2 if it failed:

Try { Set-Mailbox jsmith -AntispamBypassEnabled $false -ErrorAction Stop -WarningVariable Warn }
  Catch { Exit 2 }  
if ($Warn) { Exit 1 }
else       { Exit 0 } 

OTHER TIPS

$LastExitCode has to do with the exit code of Win32 applications, not PowerShell cmdlets. You might be better to check $? for True or False. The $? variable can report on both Win32 applications and PowerShell cmdlets. Here's the text from Get-Help about_Automatic_Variables:

$?

Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed.

You could also clear $Error, such as $Error.Clear() and then check the value of $Error[0] to see if it is populated or not after your command has run.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top