True up AD group members from Group A to Group B using PowerShell

347 0

This is an example of how to true up AD members from Group A to Group B using PowerShell. If you have ever needed to have a group mimic another groups membership, then this might be a solution for you. In this scenario, the script will look at the membership of Group A and if it is not in Group B it will add the user to it each time it is run. This will be leveraging the Get-ADGroupMember cmdlet of the Active Directory module seen here Get-ADGroupMember (ActiveDirectory) | Microsoft Learn

The script

# Trues group members from Group A to Group B
# Variables
$targetusers = Get-ADGroupMember 'GroupB'
$sourceusers = Get-ADGroupMember 'GroupA'

# Iterate over each source-user
foreach ($user in $sourceusers)
{
$test = $true
foreach ($tuser in $targetusers){if ($tuser.samaccountname -eq $user.samaccountname){$test = $false}}
if ($test){Add-ADGroupMember -Identity GroupB -Members $user}
}

Breaking it down

You will replace GroupA with the name of your group that is the source group to check against and replace GroupB with the name of the group you will add users to for matching membership of GroupA. The following lines grabs the members of each group and stores them in variables.

$targetusers = Get-ADGroupMember 'GroupB'
$sourceusers = Get-ADGroupMember 'GroupA'

The script will Initialize $test as True and then check for every user in GroupA, whether it exists in GroupB or not. If it does, then it is skipped and if it does not then it will add it to GroupB.

Final Thoughts

This may not be a use case that is needed very often, but I have actually run into the need before. Do not forget to change the group names to your specific names. It is always a good idea to test scripts in a test environment.

Find more onĀ https://notposted.com

Total 0 Votes
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

About The Author

Coolest hedgehog in town!

No Comments on "True up AD group members from Group A to Group B using PowerShell"

Leave a Comment

Your email address will not be published. Required fields are marked *