In developing a script that drops the output file to a user’s desktop it begs the question – what is the best way to determine the full path to the directory that is the user’s desktop. Below is the journey and some details on why (in my case) each option wasn’t feasible.
1st attempt – User Profile
The first option attempted is the following to use the USERPROFILE environment variable.
$DesktopPath = "{0}\Desktop" -f $env:USERPROFILE
This returns in my case C:\Users\Andrew\Desktop. Which could work in many cases, but if you are in an environment where your desktop has been stored in One Drive or the user has moved there desktop – you would then be writing the file to the wrong location.
2nd attempt – One Drive Path
The next option was to use one of the One Drive environment variables – which will depend on whether its a Corporate or Consumer user – the three options are included below. You’d need to test each to determine which might be the most appropriate for your scenario.
$DesktopPath = "{0}\Desktop" -f $env:OneDrive
$DesktopPath = "{0}\Desktop" -f $env:OneDriveConsumer
$DesktopPath = "{0}\Desktop" -f $env:OneDriveBusiness
These all return variations of the following C:\Users\Andrew\OneDrive\Desktop or C:\Users\Andrew\MYORG\Desktop
The main downsides with this approach are:
- you have to confirm which is the correct variable to use
- if a user doesn’t have One Drive installed the script would fail in that scenario and point to a directory that may not exist.
Final attempt – Get Folder Path
The most reliable (and simplest) method I’ve found was to use the Environment variable methods, which includes a function called GetFolderPath which allows you to get the correct value for a user’s desktop by passing the string “Desktop” (as shown below).
$DesktopPath = [Environment]::GetFolderPath(“Desktop”)
In my case this returns the expected value of C:\Users\Andrew\OneDrive\Desktop