Zoho Banner September 2011

Back in March 2010 when Powershell and I were on somewhat less friendly terms, I wrote an OU shadow script to populate group membership based on the contents of an OU. Since then, Powershell and I now at least acknowledge eachother when we pass in the corridor and I have updated the script with some improvements.

One common use for the script is populating group memberships for use with Fine-Grained Password Policy (FGPP).

Please leave a comment if you see any scope for improvement.  You can download a copy of the script here: OUBasedGroupMembership ps1

#########################################################
#
# Name: OUBasedGroupMembership.ps1
# Author: Tony Murray
# Version: 1.0
# Date: 03/09/2013
# Comment: PowerShell 2.0 script to
# manage group membership based on OU contents
#
#########################################################

# Import the AD module
ipmo ActiveDirectory

# Define arrays to be used for matching
$arrou = @()
$arrgp = @()

# Domain controller to be used
$dc = (Get-ADRootDSE).dnshostname
write-host "Using DC $dc for all AD reads/writes"

# Specify the OU where the accounts are located
$OUdn = "OU=Admin Accounts,OU=AD Administration,DC=contoso,DC=com"
$OuUsrs = Get-ADUser -Filter * -SearchBase $oudn -Server $dc

# Specify the group to use
$grp = "de42112f-81d2-4849-900c-d6907c77d3f5" # "Service Accounts"
$grpusers = Get-ADGroupMember -Identity $grp -Server $dc

# Build arrays using the DN attribute value
$OuUsrs | % {$arrou += $_.distinguishedname}
$grpusers | % {$arrgp += $_.distinguishedname}

# Add to group membership (new user in OU)
foreach ($usr in $arrou) {
    if ($arrgp -contains $usr) {
        write-host "User $usr is a member of the group"
    }
    else {
        write-host "User $usr is not a member of the group - adding..."
        #Add-ADGroupMember -Identity $grp -Members $usr -Server $dc
    } # end else
    Remove-Variable -ErrorAction SilentlyContinue -Name usr    
} # end foreach

write-host "`n"

# Remove from group membership (no longer in OU or has been manually added to group)
# The assumption here is that the OU is authoritative for the group's membership
foreach ($mem in $arrgp) {
    if ($arrou -contains $mem) {
        write-host "User $mem is located in the OU.  Nothing to do"
    } # end if
    else {
        write-host "User $mem is not present in the OU.  Removing from membership..."
        #Remove-ADGroupMember -Identity $grp -Members $mem -Server $dc -Confirm:$false
    } # end else
    Remove-Variable -ErrorAction SilentlyContinue -Name mem
} # end foreach

One Comment

  1. Kevin Provis says:

    Great update thank Tony

Leave a Reply