Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a command has run successfully

I've tried enclosing the following in an if statement so I can execute another command if this succeeds:

Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" | Foreach-Object {         $Localdrives += $_.Path 

but I can't figure out how to do it. I even tried creating a function but I couldn't figure out how to check if the function had successfully completed either.

like image 639
Sune Avatar asked Jan 01 '12 14:01

Sune


People also ask

How do you know if a command has been succeeded?

To get the value, run this command. $ echo $? If a command succeeded successfully, the return value will be 0. If the return value is otherwise, then it didn't run as it's supposed to.

How do I check if a previous command was executed successfully in Unix?

This works by using the (( )) arithmetic mode, so if the command returned success , i.e. $? = 0 then the test evaluates to ((0)) which tests as false , otherwise it will return true . but it's already not much shorter than the first example. After that $? is 0 if success, otherwise failure.

How do you find when a command was executed in Linux?

In Linux, there is a very useful command to show you all of the last commands that have been recently used. The command is simply called history, but can also be accessed by looking at your . bash_history in your home folder. By default, the history command will show you the last five hundred commands you have entered.


1 Answers

Try the $? automatic variable:

$share = Get-WmiObject -Class Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'"  if($?) {    "command succeeded"    $share | Foreach-Object {...} } else {    "command failed" } 

From about_Automatic_Variables:

$?    Contains the execution status of the last operation. It contains TRUE if the last operation succeeded and FALSE if it failed. ...  $LastExitCode    Contains the exit code of the last Windows-based program that was run. 
like image 140
Shay Levy Avatar answered Oct 02 '22 21:10

Shay Levy