Check if a command has run successfully

前端 未结 4 1521
轮回少年
轮回少年 2020-12-05 04:46

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 $Ser         


        
相关标签:
4条回答
  • 2020-12-05 04:54

    Or if a failure returns no standard output, that would work for an if statement:

    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:

    Get-CimInstance Win32_Share -ComputerName $Server.name -Credential $credentials -Filter "Description='Default share'" || 'command failed'
    
    0 讨论(0)
  • 2020-12-05 05:01

    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.
    
    0 讨论(0)
  • 2020-12-05 05:02

    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.

    0 讨论(0)
  • 2020-12-05 05:10

    you can try :

    $res = get-WmiObject -Class Win32_Share -Filter "Description='Default share'"
    if ($res -ne $null)
    {
      foreach ($drv in $res)
      {
        $Localdrives += $drv.Path
      }
    }
    else
    {
      # your error
    }
    
    0 讨论(0)
提交回复
热议问题