Skip to content

Instantly share code, notes, and snippets.

@kenaniah
Last active March 3, 2020 21:09
Show Gist options
  • Save kenaniah/5534987 to your computer and use it in GitHub Desktop.
Save kenaniah/5534987 to your computer and use it in GitHub Desktop.
Automatically manages "shadow groups" in Active Directory based on OUs.
<#
.SYNOPSIS
Manages Shadow Groups in Active Directory
.DESCRIPTION
This script automatically manages the member users of groups placed in
"OU=Shadow Groups,DC=mydomain,DC=local". Users and computers that are contained
by OUs that match the name of a shadow group are automatically added to that group,
and users that are no longer contained by a matching OU are removed from
the group.
This script also forces replication between domain controllers (named dc1 and dc2)
.COMPONENT
ActiveDirectory
.LINK
Author: Kenaniah Cerny <kenaniah@gmail.com>
URL: https://gist.github.com/kenaniah/5534987
#>
Import-Module ActiveDirectory
# Perform replication from dc1 to dc2
repadmin /replicate dc2 dc1 "dc=mydomain,dc=local"
# Find the shadow groups
$SHADOW_GROUPS = Get-ADGroup -Filter * -SearchBase "OU=Shadow Groups,OU=Security Groups,DC=mydomain,DC=local"
$SHADOW_GROUPS | ForEach {
# Get current group membership
$GROUP = $_
$GROUP_MEMBERS = Get-ADGroupMember -Identity $GROUP
Write-Host "=== Group:", $GROUP.name, "==="
# Find the users and computers that should belong in the group
$OUS = Get-ADOrganizationalUnit -Filter {Name -eq $GROUP.name}
$VALID_MEMBERS = @()
$VALID_MEMBERS += $OUS | ForEach { Get-ADUser -Filter * -SearchBase $_ }
$VALID_MEMBERS += $OUS | ForEach { Get-ADComputer -Filter * -SearchBase $_ }
$VALID_MEMBERS += Get-ADGroup -Identity $GROUP | Get-ADGroupMember | Where-Object { $_.objectClass -eq "group" } | ForEach { Get-ADGroupMember -Identity $_ -Recursive }
# Remove users / computers that don't belong
$GUIDS = $VALID_MEMBERS | Select -ExpandProperty ObjectGUID
$GROUP_MEMBERS | Where-Object { $GUIDS -NotContains $_.ObjectGUID } | ForEach {
if($_ -and $_.ObjectClass -ne "group"){
Remove-ADPrincipalGroupMembership -Identity $_ -MemberOf $GROUP -Confirm:$false
Write-Host "Removed:" $_.name
}
}
# Add new users / computers to the group
$GUIDS = $GROUP_MEMBERS | Select -ExpandProperty ObjectGUID
$VALID_MEMBERS | Where-Object { $GUIDS -NotContains $_.ObjectGUID } | ForEach {
if($_ -and $_.ObjectClass -ne "group"){
Add-ADPrincipalGroupMembership -Identity $_ -MemberOf $GROUP
Write-Host "Added:" $_.name
}
}
}
Write-Host
# Perform replication from dc2 to dc1
repadmin /replicate dc1 dc2 "dc=mydomain,dc=local"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment