Migrate Home Directories to New File Server

This code loops through all of the search results and outputs the needed powershell script to move users home directories to the new file server.  The example Active Directory searches for users matching an existing old file server path in their home directory.  You can copy the results to a file and make any individual changes if needed. It is important to note that Active Directory queries are limited to 1,000 results.

 

#Home Directory Migration
Import-Module ActiveDirectory
$dom = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
$root = $dom.GetDirectoryEntry()
$search = [System.DirectoryServices.DirectorySearcher]$root

#This finds all of the existing users with the specified home directory
#In Active Directory Searching the back slash has to be escaped by using "\5c"
#Search Filter Syntax https://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx
$search.Filter = "(&(&(objectCategory=person)(objectClass=user))((homeDirectory=*\5c\5cOldFileServer\5chome*)))" #<-Looks for existing H drive in \\old\share*
$result = $search.FindAll()

#Output the desired script
#How to install Remote AD Tools https://4sysops.com/archives/how-to-install-the-powershell-active-directory-module/
Write-Host "Import-Module ActiveDirectory"
#Write out to a file
$textout = "Import-Module ActiveDirectory"
$textout > ".\MigrateHomeDirectories.ps1"

#Get-ADUser -LDAPFilter "(sAMAccountName=$folder)"
foreach ($user in $result)
{
    $username1 = $($user.properties.samaccountname) 
    $homedir = $($user.properties.homedirectory)
    
    #export out the existing data if you want
    #Write-Host "$username1,""$homedir"""
        
    #Replace uses double back slashes "\\" instead of "\5c" for escaping back slashes and the replacement string does not need to be escaped for backslashes
    #Replacing Text http://blogs.technet.com/b/heyscriptingguy/archive/2011/03/21/use-powershell-to-replace-text-in-strings.aspx
    $newhomedir = $homedir -replace "\\\\OldFileServer\\home\\","\\NewFileServer\home\"
    #Write-Host $newhomedir
    #Output the desired script
    Write-Host "Set-ADUser '$username1' -HomeDirectory '$newhomedir' -homedrive 'H:'"

    #Write out to a file
    $textout = "Set-ADUser '$username1' -HomeDirectory '$newhomedir' -homedrive 'H:'"
    $textout >> ".\MigrateHomeDirectories.ps1"

   
	
}

Leave a Reply

%d bloggers like this: