Check if a command has run successfully

前端 未结 4 1527
轮回少年
轮回少年 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 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.

提交回复
热议问题