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.
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.
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.
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.
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.
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