Forum Discussion
Script to balance AD group membership.
# Define the AD groups
$groupNames = @(
"Group1", # Replace with actual group names
"Group2",
"Group3"
# Add more groups as needed
)
# Function to get members of each group
function Get-GroupMembers {
param (
[string]$groupName
)
return Get-ADGroupMember -Identity $groupName | Where-Object { $_.ObjectClass -eq "user" }
}
# Function to distribute members
function Distribute-Members {
param (
[array]$groupNames
)
# Create an array to store members and group sizes
$groupMembers = @{}
$totalMembers = 0
# Get the current members of each group
foreach ($groupName in $groupNames) {
$members = Get-GroupMembers -groupName $groupName
$groupMembers[$groupName] = $members
$totalMembers += $members.Count
}
# Calculate the target number of members per group
$numGroups = $groupNames.Count
$targetMembersPerGroup = [math]::Ceiling($totalMembers / $numGroups)
# Create an array to store the excess members to redistribute
$excessMembers = @()
# Loop through each group and identify excess members
foreach ($groupName in $groupNames) {
$currentGroupSize = $groupMembers[$groupName].Count
if ($currentGroupSize > $targetMembersPerGroup) {
$excessMembers += $groupMembers[$groupName] | Select-Object -First ($currentGroupSize - $targetMembersPerGroup)
$groupMembers[$groupName] = $groupMembers[$groupName] | Select-Object -Skip ($currentGroupSize - $targetMembersPerGroup)
}
}
# Now redistribute the excess members to the groups with fewer members
foreach ($groupName in $groupNames) {
$currentGroupSize = $groupMembers[$groupName].Count
while ($currentGroupSize < $targetMembersPerGroup -and $excessMembers.Count -gt 0) {
$groupMembers[$groupName] += $excessMembers[0]
$excessMembers = $excessMembers[1..($excessMembers.Count - 1)]
$currentGroupSize++
}
}
# Add the redistributed members back to the AD groups
foreach ($groupName in $groupNames) {
$membersToAdd = $groupMembers[$groupName]
$existingMembers = Get-GroupMembers -groupName $groupName
# Filter out existing members to avoid duplicates
$membersToAdd = $membersToAdd | Where-Object { $_.DistinguishedName -notin $existingMembers.DistinguishedName }
if ($membersToAdd.Count -gt 0) {
# Add the members to the group
Add-ADGroupMember -Identity $groupName -Members $membersToAdd
Write-Host "Added $($membersToAdd.Count) members to $groupName"
}
}
}
# Execute the function to redistribute the members
Distribute-Members -groupNames $groupNames