Forum Discussion

Skipster311-1's avatar
Skipster311-1
Iron Contributor
Aug 18, 2021

need help with script

Hello all   I am trying to mimic the behavior of a dynamic group. This is for on-prem AD.  This is what i have to do.   #1 check two OU's  If user live in the Corp\Consultants\* or Corp\FM...
  • pvanberlo's avatar
    Aug 18, 2021

    Skipster311-1 I would do it like this. It looks complex, but you need to take into account that you want to identify users to be removed as well. So we first gather all group members and expect them all to be removed. Then we check both OUs and if a user in those OUs is present in the group, set their action to do nothing, and if a user is not present yet, it's obviously a new user so should be added. This then leaves all the rest set to be removed. At the end we then do the actual action.

     

    This was quick and dirty, not optimized, and may contain mistakes 😉 It could be optimized to do the OU checks in a function etc to avoid code duplication.

     

    $GroupMembers = @{}
    ForEach ($User in Get-ADGroupMember -Identity Example1) {
        $GroupMembers.Add($User.DistinguishedName, @{"DN"=$User.DistinguishedName;"Action"="Remove"})
    }
    
    ForEach ($User in Get-ADUser -SearchBase "OU=Consultants,DC=Test,DC=local" -Filter *) {
        if (!$GroupMembers[$User.DistinguishedName]) {
            # User found in OU, but not in group yet --> Add user
            $GroupMembers.Add($User.DistinguishedName, @{"DN"=$User.DistinguishedName;"Action"="Add"})
        } else {
            # User found in OU, and also present in group --> Do Nothing
            $GroupMembers[$User.DistinguishedName].Action = "Nothing"
        }
    }
    
    ForEach ($User in Get-ADUser -SearchBase "OU=FM Users,DC=Test,DC=local" -Filter *) {
        if (!$GroupMembers[$User.DistinguishedName]) {
            # User found in OU, but not in group yet --> Add user
            $GroupMembers.Add($User.DistinguishedName, @{"DN"=$User.DistinguishedName;"Action"="Add"})
        } else {
            # User found in OU, and also present in group --> Do Nothing
            $GroupMembers[$User.DistinguishedName].Action = "Nothing"
        }
    }
    
    ForEach ($User in $GroupMembers.Values) {
        if ($User.Action -eq "Add") {
            Write-Host "Adding $($User.DN) to group"
            Add-ADGroupMember -Identity Example1 -Members $User.DN
        }
        if ($User.Action -eq "Remove") {
            Write-Host "Removing $($User.DN) from group"
            Remove-ADGroupMember -Identity Example1 -Members $User.DN -Confirm:$false
        }
    }

     

Resources