Sunday, February 24, 2013

Search and replace ProfilePath in Active Directory with PowerShell

  1. Test the actions below first in an test Active Directory environment before you run this in an production environment!
  2. Start PowerShell as an Administrator (Shift key + Right click mouse)
  3. Type: Set-ExecutionPolicy Unrestricted
  4. Save the PowerShell code below as: ChangeUserProfilePath.ps1
# Search and replace ProfilePath for user accounts in Active Directory                 
# Change the old_servernamen and new_servername too your own server names  

$RootDN = [ADSI] ''

$Searcher = New-Object System.DirectoryServices.DirectorySearcher($RootDN)

$Sorter = New-Object System.DirectoryServices.SortOption
$Sorter.PropertyName = "sAMAccountName"

$Searcher.Filter = "(&(objectCategory=person)(objectClass=user))"
$Searcher.Sort = $Sorter

$Users = $Searcher.FindAll()

Write-Host "There are" $Users.Count "users in the Active Directory"

$i = 0

ForEach ($User in $Users) {

# Fail safe code. Prompt every 5 records.

If (($i % 1000) -eq 0) {

Write-Host
Write-Host "I have processed 1000 records... should I continue?"
Write-Host "To Cancel, press Ctrl+Break"

While ($Response -ne "Y") {
$Response = Read-Host "Type Y and press [Enter] to continue."
}

Write-Host

}

$UserDN = [ADSI]$User.Path

$UserprofilePath = $UserDN.profilePath.ToString()
$UserAccountName = $UserDN.sAMAccountName.ToString()

If ($UserprofilePath.ToLower().Contains('\\old_server\profiles$'.ToLower())) {

Write-Host $UserDN.sAMAccountName","$UserDN.displayName","$UserDN.profilePath

$NewProfilePath = $UserDN.profilePath.ToString().ToLower()
$NewProfilePath = $NewProfilePath.Replace("\\old_server\profiles$", "\\new_server\Profiles$")

Write-Host $NewProfilePath
Write-Host

# NB: Only uncomment the lines below when you are absolutely
# sure you wish to run the script.
$UserDN.Put("profilePath", "$NewProfilePath")
$UserDN.SetInfo()

}

$Response = ""
$i++
}

4. Change the old and new servernames as described in first three line in the script and save it.
5. Run the ChangeUserProfilePath.ps1 script.
6. Check in Active Directory if the profile path is changed correct.

No comments: