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