Thursday, December 9, 2010

Powershell Script to Swap Two Active Directory Attributes

Background

It is simple to access AD with Powershell and manipulate attributes and LDAP entries much the same as in VB.Net or C#. This Powershell script performs a simple swap of two attributes (specifically first name and last name) for all objects in and below a container in active directory using a subtree search (I picked an organizational unit in this case). It should be easily modifiable for other purposes (changing a value for all users, computers, groups, etc.)

The Script (SwapADAttrs.ps1)

# Developed by Mike Burr # Swap attributes on Active Diretory Objects 
# 12/9/2010 
# This application is provided AS IS with no warranties.  

$Searcher = New-Object System.DirectoryServices.DirectorySearcher   
# Need a couple of things: 
#  - Base Distinguished Name for the LDAP search 
#  - Scope: Base, Onelevel, Subtree 
#  - Filter for the objects that should be returned by the search 
#  

$Filter = "(ObjectCategory=Person)" 
$BaseDN = "LDAP://OU=ToSwap,DC=mikesdevblog,DC=local" 
$Searcher.SearchScope = [System.DirectoryServices.SearchScope]::Subtree 

$Searcher.Filter = $Filter 
$Searcher.SearchRoot = $BaseDN  

#Get all of the objects that match 
$Result = $Searcher.FindAll()  

#Properties to Swap 
$Property1 = "givenName" 
$Property2 = "sn"  

#Swap the attribute values for all of the objects 
foreach ($Object in $Result) {     
     $DirectoryEntry = $Object.GetDirectoryEntry()
     $Temp = $DirectoryEntry.Properties.$Property1.Value
     $DirectoryEntry.Properties.$Property1.Value = $DirectoryEntry.Properties.$Property2.Value     
     $DirectoryEntry.Properties.$Property2.Value = $Temp      
$DirectoryEntry.CommitChanges() }  

Beginning and End Output from LDP

----------- ***Searching... ldap_search_s(ld, "OU=ToSwap,DC=mikesdevblog,DC=local", 2, "(objectCategory=Person)", attrList,  0, &msg) 

Getting 2 entries: Dn: CN=First1 Last1,OU=ToSwap,DC=mikesdevblog,DC=local    
    givenName: First1;  
    objectCategory: CN=Person,CN=Schema,CN=Configuration,DC=mikesdevblog,DC=local;      
    sn: Last1;   

Dn: CN=First2 Last2,OU=ToSwap,DC=mikesdevblog,DC=local
    givenName: First2; 
    objectCategory: CN=Person,CN=Schema,CN=Configuration,DC=mikesdevblog,DC=local;  
    sn: Last2;   

----------- 
***Searching... ldap_search_s(ld, "OU=ToSwap,DC=mikesdevblog,DC=local", 2, "(objectCategory=Person)", attrList,  0, &msg) 
Getting 2 entries: 
Dn: CN=First1 Last1,OU=ToSwap,DC=mikesdevblog,DC=local 
    givenName: Last1; 
    objectCategory: CN=Person,CN=Schema,CN=Configuration,DC=mikesdevblog,DC=local;  
    sn: First1;   

Dn: CN=First2 Last2,OU=ToSwap,DC=mikesdevblog,DC=local
    givenName: Last2; 
    objectCategory: CN=Person,CN=Schema,CN=Configuration,DC=mikesdevblog,DC=local;  
    sn: First2;   
-----------  

No comments:

Post a Comment