Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Import-Module ActiveDirectory
(Get-ADGroup -Identity $ShadowGroup -properties members).Members | Get-ADUser | Where-Object {$_.distinguishedName –NotMatch $OU} | ForEach-Object {Remove-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup –Confirm:$false}
Get-ADUser –SearchBase $OU –SearchScope OneLevel –LDAPFilter "(!memberOf=$ShadowGroup)" | ForEach-Object {Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup}
$WhatIf=$true #set $true for testing and $false for action
Import-Module ActiveDirectory
Write-Host "Removing non-existent members"
#$RemoveMembers = (Get-ADGroupMember -Identity $ShadowGroup | Where-Object {$_.distinguishedName -NotMatch $OU}) #Fails for more than 5000
$RemoveMembers = ((Get-ADGroup -Identity $ShadowGroup -properties members).Members | Get-ADUser | Where-Object {$_.distinguishedName -NotMatch $OU}) #workaround for 5000 limit
$RemoveMembers | ForEach-Object {Write-Host -NoNewline $_.SamAccountName ": " ; Remove-ADPrincipalGroupMembership -Identity $_ -MemberOf $ShadowGroup -Confirm:$false -WhatIf:$WhatIf -Verbose}
Write-Host "Adding members"
$AddMembers=(Get-ADUser -SearchBase $OU -SearchScope OneLevel -LDAPFilter "(!memberOf=$ShadowGroup)")
$AddMembers | ForEach-Object {Write-Host -NoNewline $_.SamAccountName ": " ; Add-ADPrincipalGroupMembership -Identity $_ -MemberOf $ShadowGroup -WhatIf:$WhatIf -Verbose}
# Emailing
if ($RemoveMembers -or $AddMembers) {
$from = "$env:COMPUTERNAME <>"
$subject = "Automated script: ShadowGroup: "+($ShadowGroup -split ',*..=')[1]
$body="The following shadows applied between: <br>"
$body+="OU: $OU <br>"
$body+="Group: $ShadowGroup <br><br>"
if ($WhatIf) { $body+="TESTING ONLY<br><br>"}
foreach ($rm in $RemoveMembers) {
$body+="Removed $sName <br>"
if ($RemoveMembers) {$body+="<br>"}
foreach ($am in $AddMembers) {
$body+="Added $sName <br>"
Write-host "Emailing $adminEmailAddr"
$textEncoding = [System.Text.Encoding]::UTF8
try {
Send-Mailmessage -smtpServer $smtpServer -from $from -to $adminEmailAddr -subject $subject -body $body -bodyasHTML -priority High -Encoding $textEncoding -ErrorAction Stop -ErrorVariable err
} catch {
write-host "Error: Failed to email $adminEmailAddr via $smtpServer"
} finally {
if ($err.Count -eq 0) {
write-host "Successfully emailed $adminEmailAddr"
} else {
Write-Host "Nothing to email."

This comment has been minimized.

Copy link
Owner Author

commented Mar 27, 2018

contains an important bug fix: required -properties members in the Get-ADGroup cmdlet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.