Powershell OU Shadow Script
It is sometimes useful to have the ability to populate group membership based on the OU in which the prospective members are located. A good example of where this might be useful is with Fine-Grained Password Policy (FGPP) in Windows Server 2008 AD (and later). FGPP does not have the ability to use an OU as its scope of management - you are limited to assigning the policy to user or group objects.
The script below shadows a specified OU and populates a group’s membership based on the contents of the OU. It is intended to be invoked by the Windows Task Scheduler (taskschd.msc).
Note that it requires Powershell 2.0 and uses the Active Directory module.
#########################################################
#
# Name: OUShadow.ps1
# Author: Tony Murray
# Version: 1.0
# Date: 26/03/2010
# Comment: PowerShell 2.0 script to set the members of
# a group based on the OU they live in
#
#########################################################
#Import the Active Directory Powershell Module
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
#Set Variables
$Group = "OU Shadow"
$SearchBase = "OU=User Accounts,DC=Contoso,DC=Com"
$MbrArr = get-adgroupmember -identity $Group
$OUArr = Get-ADUser -LDAPFilter "(samaccounttype=805306368)" -SearchBase $SearchBase
# Loop through the Users found in the OU
# and check to see if the user is already
# a member of the group.
Foreach ($User in $OUArr)
{
if ($MbrArr -Match $User.distinguishedName)
{
# The user is already member - do nothing
}
else
{
# We need to add the user as a member
Add-ADGroupMember -Identity $Group -Members $User
}
}
# Loop through the group membership and remove
# any users that are not in the OU
Foreach ($Mbr in $MbrArr)
{
if ($OUArr -Match $Mbr.distinguishedName)
{
# Found user in OU - do nothing
}
else
{
# We need to remove the user as a member
Remove-ADGroupMember -Identity $Group -Members $Mbr -confirm:$false
}
}
# End
Comments(1)