views:

33

answers:

1

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

+2  A: 

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.

Keith Hill
thanks for the answer. So i'm assuming that `$?` and `$LastExitCode` are relative? Suppose I execute this (or another) cmd throughout the script- those vars are relative to the last command that was executed?
baron
Exactly. `$?` applies to all command execution. It indicates success for the previous most command. Note that non-terminating errors (Get-ChildItem idontexist) still result in a `$?` returning true. If a command throws a terminating error then `$?` returns $false. If necessary you can force a command to convert a non-terminating error into a terminating error by using the ubiquitous parameter `-ErrorAction Stop`. `$LastExitCode` holds the exit code for the most recently executed EXE.
Keith Hill