Identifying User Profile

by Sep 23, 2020

Be careful when using $env:userprofile or $home to create paths to user files. When a Windows box is set up for OneDrive, the documents folder may have been redirected to a subfolder named “OneDrive”. Here are some examples:

 
PS> $env:USERPROFILE
C:\Users\tobia

PS> $HOME
C:\Users\tobia

PS> $profile
C:\Users\tobia\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1

PS> 
 

As you see, the PowerShell profile script does not reside in the Documents folder directly inside the user profile. Instead, it moved into a subfolder named “OneDrive”.

To find the current Documents folder, use GetFolderPath() instead:

 
PS> [Environment]::GetFolderPath('MyDocuments')
C:\Users\tobia\OneDrive\Documents
 

You can even use this to determine whether or not OneDrive redirected user files:

$redirected = [Environment]::GetFolderPath('MyDocuments') -like '*\OneDrive\*'
$redirected 

This returns $true when OneDrive redirected folders, else $false.


Twitter This Tip! ReTweet this Tip!