Search This Blog

Thursday, August 12, 2010

Powershell script to put migrated users into a group

My friend Tony Murray has written a very good script that helps you keep track of migrated users that I wanted to share:

Note: I couldn't get the tabs in so it looks a little funny :(

-Script Begins-

#########################################################

#
# Name: SIDHistoryBasedGroupMembership.ps1
# Author: Tony Murray
# Version: 1.0
# Date: 11/07/2010
# Comment: PowerShell 2.0 script to
# populate group membership based on sIDHistory values
#
#########################################################


#Import the Active Directory Powershell Module
Import-Module ActiveDirectory -ErrorAction SilentlyContinue


#Create a new Event log source for the script (only needs to be run once)
New-EventLog -logName Application -Source "Legacy Users Group Management" `
-ErrorAction SilentlyContinue


$SearchBase = "OU=User Objects,DC=fabrikam,DC=local"
$OUArr = Get-ADUser -LDAPFilter "(samaccounttype=805306368)" `
-SearchBase $SearchBase -SearchScope SubTree


# Now we need the domain security identifier or at least a portion of it
$DomSID = "S-1-5-21-1584567894-2535104369-4141123456"


$Group = "Legacy Users"
$MbrArr = get-adgroupmember -identity $Group


# Loop through the Users found beneach the OU tree
# and check to see if the user is already
# a member of the group. If so, do nothing.
# If not, then add the user as a member.
Foreach ($User in $OUArr)
{
$object = [ADSI]"ldap://$User/"
$objectsidh = $object.sIDHistory.value
If (!$objectsidh)
{
# write-host "sIDHistory is blank"
}
Else
{
$objectsidh = $Object.getex(“sidhistory”)
trap
{
#write-host "Error: $_"
continue
}
foreach($sid in $objectSidh)
{
$sidh = new-object System.Security.Principal.SecurityIdentifier $sid,0
if ($sidh -Match $DomSID)
{
if ($MbrArr -Match $User.distinguishedName)
{
#The user is already member - do nothing
}
else
{
# We need to add the user as a member
write-eventlog -logname Application `
-source "Legacy Users Group Management" `
-eventID 3001 -entrytype Information -message "$User added to $Group"
Add-ADGroupMember -Identity $Group -Members $User
}
}
else
{
# No match with sidHistory - do nothing
}
}
}
}
 
-Script Ends-