Sune
Sune

Reputation: 3280

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.

Upvotes: 65

Views: 159426

Answers (6)

JPBlanc
JPBlanc

Reputation: 72680

you can try :

$res = get-WmiObject -Class Win32_Share -Filter "Description='Default share'"
if ($null -ne $res)
{
  foreach ($drv in $res)
  {
    $Localdrives += $drv.Path
  }
}
else
{
  # your error
}

Upvotes: 22

Manthan
Manthan

Reputation: 1

Function CommandStatus ($Status) {
 if ($status -eq $true) {
      Write-Host "Success!" 
    } else {
      Write-Host "Failed!" 
    }
}

Upvotes: 0

Shay Levy
Shay Levy

Reputation: 126912

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 command. 
   It contains True if the last command succeeded and False if it failed.
...

$LastExitCode
   Contains the exit code of the last native program or PowerShell script that ran.

Upvotes: 141

js2010
js2010

Reputation: 27606

Or if a failure returns no standard output, that would work for an if statement (assuming an exception doesn't terminate the pipeline):

if (! (Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'")) { 
  'command failed'
}

Also there's now the or symbol "||" in powershell 7 (works with terminating exceptions):

Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" || 'command failed'

Upvotes: 4

chepilov
chepilov

Reputation: 3

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

“execute first command”
if($error.count -eq 0)
{
   “execute second command”
}

if you want to clear the errors afterwards you can use: $error.clear(). This will set the counter of errors to 0.

Upvotes: 0

Kdships
Kdships

Reputation: 13

There are instances where any of the options are best suitable. Here is another method:

try {
Add-AzureADGroupMember -ObjectId XXXXXXXXXXXXXXXXXXX -RefObjectId (Get-AzureADUser -ObjectID "XXXXXXXXXXXXXX").ObjectId  -ErrorAction Stop
Write-Host "Added successfully" -ForegroundColor Green
$Count = $Null
$Count = 1
}
catch {
$Count = $Null
$Count = 0
Write-Host "Failed to add: $($error[0])"  -ForegroundColor Red
}

With try and catch, you don't only get the error message returned when it fails, you also have the $count variable assigned the number 0. When the command is successful, your $count value returns 1. At this point, you use this variable value to determine what happens next.

Upvotes: 1

Related Questions