Determining if a Powershell command was successful

baron picture baron · Oct 21, 2010 · Viewed 36k times · Source

Hi I am quite new to Powershell but I have one niggling question. I want to be able to tell if a command has completed successfully so I can give meaningful messages to host.

I am using the appcmd command to add a binding in IIS. Essentially that goes as follows:

./appcmd set site /site.name:........................

But how can I do a check to ensure it was successful or not?

I think if I just put Write-Host "Successfully added binding" after that statement it will fire after regardless if the appcmd was successful.

I'm guessing I need to do something like:

$successful = ./appcmd set site /site.name:........................

but then $successful seems to be a string containing the msg result?

Grateful any help on this! Cheers

Answer

Keith Hill picture Keith Hill · Oct 21, 2010

Assuming appcmd is a console exe, even if it errors, the next line in the script will execute.

If you want to test if the EXE errored and the EXE uses the standard 0 exit code to indicate success, then just inspect the $? special variable right after calling the EXE. If it is $true, then the EXE returned a 0 exit code.

If the EXE is non-standard in terms of the exit code it returns for success (perhaps it has multiple success codes) then inspect $LastExitCode to get the exact exit code the last EXE returned.