A way to skip accounts that already exist?

Hey everyone,

Hoping someone can help with this. I have the command below that copies users in an OU to a security group…

Get-ADUser -SearchBase “OU=Marine Group,OU=New OUs,DC=corpycorp,DC=local” -Filter * | % {Add-ADGroupMember ‘marinegroupmfa’ -Members $_}

Works great and I want to automate this as a scheduled task so that anytime a new user is added, it will then also be added to my AD group. The problem is that every time I run it, I get this error stating all the existing accounts already exist, x 100 or so depending on number of users in the OU…

Add-ADGroupMember : The specified account name is already a member of the group

At line:1 char:103

  • … C=com" -Filter * | % {Add-ADGroupMember ‘BoulderCorpMFA’ -Members $_}

  •                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    

 

It still runs fine but I’d like for it to run clean and only copy newly added users. Is there a way to do this?

Thanks in advance!

Nelson

Try/Catch block should do the trick. In your catch block, use Write-Warning or Write-Output so the script does not terminate and continues to try to add new members to the group.

Try {
    Get-ADUser -SearchBase "OU=Marine Group,OU=New OUs,DC=corpycorp,DC=local" -Filter * | 
    ForEach-Object {
        Add-ADGroupMember 'marinegroupmfa' -Members $_ -ErrorAction Stop
    }
}
Catch {
     Write-Warning "User already exists" # Or Write-Output
}

pwshliquori

Thanks! I just tried running it and the script appears to stop. Removed a few users as a test and it does not re add the users.

Sorry. Gave you the wrong syntax.

Get-ADUser -SearchBase "OU=Marine Group,OU=New OUs,DC=corpycorp,DC=local" -Filter * |
ForEach-Object {
    Try {
        Add-ADGroupMember 'marinegroupmfa' -Members $_ -ErrorAction Stop
    }
    Catch {
        Write-Warning "User already exists" # Or Write-Output
    }
}

Yes, now it ran correctly.

Thanks so much for your help!!!