Public/Rename-UserProfile.ps1
|
function Rename-UserProfile { <# .SYNOPSIS Renames a Windows user profile path and updates all registry references. .DESCRIPTION Recursively searches the entire Windows registry to replace all references to an old user profile path with a new path, then renames the physical profile folder. .PARAMETER OldPath The full path to the existing user profile folder. .PARAMETER NewPath The full path where the profile folder should be moved to. .PARAMETER LogPath Optional path to a log file where operation details will be written. .PARAMETER Force Force the operation without prompting for confirmation. .EXAMPLE Rename-UserProfile -OldPath "C:\Users\OldUser" -NewPath "C:\Users\NewUser" Renames the user profile from OldUser to NewUser. #> [CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')] param( [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$OldPath, [Parameter(Mandatory = $true, Position = 1, ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string]$NewPath, [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)] [string]$LogPath, [Parameter()] [switch]$Force ) process { if ($Force -and -not $Confirm) { $ConfirmPreference = 'None' } if ($PSCmdlet.ShouldProcess("$OldPath -> $NewPath", "Rename user profile")) { try { $result = [ProfileRenameHelper]::RenameUserProfile($OldPath, $NewPath, $LogPath) if ($result) { Write-Host "Successfully renamed profile from $OldPath to $NewPath" -ForegroundColor Green } else { Write-Warning "Profile rename completed with some errors. Check log file for details." } return $result } catch { Write-Error -Message $_.Exception.Message -ErrorId 'ProfileRenameFailed' -Category InvalidOperation -TargetObject $OldPath return $false } } } } |