Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if a Powershell command was successful

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

like image 232
baron Avatar asked Oct 20 '10 23:10

baron


People also ask

How do I know if a PowerShell script ran successfully?

You can use “$error” automatic variable. This will check if the first command throws error or if it completes successfully.

How do I check the status of a PowerShell script?

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.

How do I view PowerShell command history?

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.

What is $_ PowerShell?

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.


1 Answers

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.

like image 108
Keith Hill Avatar answered Sep 23 '22 19:09

Keith Hill