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
You can use “$error” automatic variable. This will check if the first command throws error or if it completes successfully.
Use one of the two variables PowerShell provides to determine the status of the last command you executed: the $lastExitCode variable and the $? variable. The $lastExitCode PowerShell variable is similar to the %errorlevel% variable in DOS. It holds the exit code of the last application to exit.
Using the F8 key, you can find the command in history that matches the text on the current command line. For example, enter get- and press F8 . The last entry in the command history matching this text will be found. To go to the next command in history, press F8 again.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With