We have a Group that is made up of managers (those with direct reports) and want to run a PS script routinely to add and remove members of the group. I would think emptying and repopulating the group members would be the most efficient, but also wanted to see the changes as a sanity check.
Here is what I came up with, but was wondering if there is a more efficient or elegant way to accomplish this.
if (-not (Get-Module ActiveDirectory)){
Import-Module ActiveDirectory
}
$ExistingDirectReportMembers = Get-ADGroupMember -Identity 'users with direct reports'
| Get-ADUser -Properties SamAccountName | Sort-Object SamAccountName
$NewUserWithDirectReports = Get-ADUser -Filter {( directReports -like "*")
-and (enabled -eq $true)} -Properties SamAccountName
| Sort-Object SamAccountName
$UsersToAdd = Compare-Object –referenceobject $ExistingDirectReportMembers
–differenceobject $NewUserWithDirectReports -Property SamAccountName
| where{$_.SideIndicator -eq "<="}
$UsersToRemove = Compare-Object –referenceobject $ExistingDirectReportMembers
–differenceobject $NewUserWithDirectReports -Property SamAccountName
| where{$_.SideIndicator -eq "=>"}
Write-Host "`nUser count BEFORE Update:" $ExistingDirectReportMembers.Count
"`nUsers removed:"
ForEach ($user in $UsersToRemove)
{
Write-Host $user.SamAccountName
Get-ADUser -Identity $user.SamAccountName
| Remove-ADGroupMember -Identity 'srs users with direct reports'
}
"`nUsers added:"
foreach ($user in $UsersToAdd)
{
Write-Host $user.SamAccountName
Get-ADUser -Identity $user.SamAccountName
| Add-ADGroupMember -Identity 'srs users with direct reports'
}
$FinalDirectReportMemberCount = Get-ADGroupMember
-Identity 'users with direct reports' | Select-Object SamAccountName
Write-Host "`nUser count AFTER Update:" $FinalDirectReportMemberCount.Count