Moving User Profiles with PowerShell

Something that comes up with some frequency on Terminal Servers (or “Remote Desktop Servers”), but perhaps sometimes in VDI, is “How to I move a user profile from one drive to another”. The traditional answers include the use of the user profile management GUI, or some expensive piece of software. But what if you need to automate the job? Or if you don’t have any money for the project?

Answer? PowerShell, of course… and robocopy.

Below is a code snippet that will set existing user profiles to load from “C:Users” to “E:Users”:
[powershell]
#Collect profile reg keys for regular users ("S-1-5-21" excludes local admin, network service, and system)
$profiles = gci -LiteralPath "HKLM:SOFTWAREMicrosoftWindows NTCurrentVersionProfileList" `
| ? {$_.name -match "S-1-5-21-"}

foreach ($profile in $profiles) {
#Set the registry path in a format that can be used by the annoyingly demanding "get-itemproperty" cmdlet:
$regPath = $(
$($profile.pspath.tostring().split("::") | Select-Object -Last 1).Replace("HKEY_LOCAL_MACHINE","HKLM:")
)

#Get the current filesystem path for the user profile, using get-ItemProperty"
$oldPath = $(
Get-ItemProperty -LiteralPath $regPath -name ProfileImagePath
).ProfileImagePath.tostring()

#Set a varialble for the new profile filesystem path:
$newPath = $oldPath.Replace("C:","E:")

#Set the new profile path using "set-itemproperty"
Set-ItemProperty -LiteralPath $regPath -Name ProfileImagePath -Value $newPath
}

#Now copy the profile filesystem directories using "robocopy".
[/powershell]

But this code will not actually move the data. For that, we need robocopy. Make sure that your users are logged off before performing this operation, otherwise “NTUSER.DAT” will not get moved, and your users will get a new TEMP profile on next login:
[cmd]
robocopy /e /copyall /r:0 /mt:4 /b /nfl /xj /xjd /xjf C:users e:Users
[/cmd]

Finally, be sure to set the default location for new profiles and the “Public” directory to your new drive as well. For that, run “Regedit”, then go to:
HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersionProfileList
and set new paths for the registry strings “ProfilesDirectory” and “Public”. Moving the default user profile is optional.

Oh yeah… you might want to purge the old Recycle Bin cruft for your moved users as well:
[cmd]
rmdir /s /q C:$Recycle.Bin
[/cmd]