TRY CATCH IF – Error handling

So I’m struggling to understand why powershell doesnt let me work with multiple IFs and CATCHES.

For example:

I want to try to add a member to a group and if that doesn’t exist to try another group, and if that doesnt work try another and so on.

But I cannot use multiple catches/ifs as part of powershell

Ideally what I would have is below, but it doesn’t work:

try {Add-ADGroupMember -Identity $Groupname1 -Members $Membersaftersplit} catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {if ($_.Exception.Message -match "Cannot find an object with identity") {Add-ADGroupMember -Identity $GroupName2 -Members $Membersaftersplit} catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {if ($_.Exception.Message -match "Cannot find an object with identity") {Add-ADGroupMember -Identity $ADGroupnamE3 -Members $Membersaftersplit} } 

submitted by /u/789qwe
[link] [comments]

Leave a Reply