Tuesday, March 13, 2018

Finding the user profile path for a user in PowerShell

Windows user profile folders are not always named exactly the same as the SAM account name. This happens when there are collisions between local and domain accounts, but can also happen when there shouldn't be conflicts -- my laptop decided to tack on the first two characters of my last name even though the SAM account name for my Microsoft account is just my first name.

To get the user profile folder for a user identified by a SAM name, PowerShell scripts can do this:

$sid = (Get-LocalUser $UserName).SID.Value.ToString()
$profile = gwmi Win32_UserProfile | ? { $_.SID -eq $sid }
$profileFolder = $profile.LocalPath

If the Get-LocalUser cmdlet is unavailable (e.g. on relatively old versions of Windows), that first line can be replaced with another WMI query:

$sid = (gwmi Win32_UserAccount | ? { $_.Name -eq $UserName }).SID

No comments:

Post a Comment