Get Logged-On User's Home Drive Location – Get-CimInstance

When using PowerShell, have you come across the need to capture the logged-on user's home drive location? In a previous post, I focussed only on a method to get a logged-on user's username. Once you have the username, you can extend the process to split the $Home variable which at that time, targets the user profile of the elevated user. The user running the PowerShell session may differ from the logged-on user, but the 'Users' folder will be shared for all on Windows. This is what makes this approach possible.

NB: For more information on PowerShell environment variables like $Home, please see this link.

With that said, just 2 lines of code will mean you have the logged-on user's username and their home drive location too. These values will be stored as variables meaning you can call on them when needed in your scripts.

2 Lines of Code to Get Logged-On User's Home Drive Location

Take the code from below and copy then paste it into your PowerShell session.

# Use Win32_ComputerSystem class, return just the username then split.
# Customise to select just the username data after the slash - No domain
$LoggedOnUser = (Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object UserName).UserName.Split('\')[1] 

# Populate $LoggedOnUserHome with the path to the user's home drive regardless of it's location
$LoggedOnUserHome = "$($Home.Split($($LoggedOnUser))[0])$($LoggedOnUser)" 

# Test the output of the code
$LoggedOnUser

# Test the output of the code
$LoggedOnUserHome

Now that you have done that, let's do some additional testing. I would advise running a PowerShell session as a different user. Input the username & password for any other domain user. Check that $Home returns the home drive location for the user that is authenticated to the PowerShell session.

Now move on to run the code above and check what values are set to each of the variables. Corresponding values will match the logged-on user and not the user that is authenticated to the PowerShell session.

For examples of where this code can be used in practice, please read:

Would you like to buy Alan a coffee?

Visit the AlanPs1 Ko-fi page

So be sure to try this out for yourself and use the code provided for any of your projects.

Thanks for reading,

Alan