Using PowerShell to get the logged-on user's username is an important technique to have in your armoury. When scripting and tooling, the need will arise to target the logged-on user. Running an elevated PowerShell session may require the target to be the logged-on domain user. Generally, this technique will be useful when targeting domain-joined computers or domain identities.
The administrator could have remoted on to a desktop. They could be using an elevated administrator PowerShell session. Administrators could also be using Invoke-Command with PowerShell Remoting. Another possibility is when using SCCM to deploy or update an asset, you might just need the logged-on user's username?
For examples of where this example can be used in practice, please see:
- Re-profile Microsoft Teams and Clear Cache PowerShell Script
- Simple WPF App Re-Profile Microsoft Teams
Windows Logged-On User's Username PowerShell 1-Liner
Using Get-CimInstance -ClassName Win32_ComputerSystem holds the key. The out the box username field is predefined with [Domain]\. This highligts additional effort will be required to get just the username. The example below will get you just the username. The username value will be loaded to a variable called $LoggedOnUser.
# 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('\')
# Test the output of the code
Try it for yourself. Can I suggest as a basic test, where you run a PowerShell session as a different user?
Authenticate to PowerShell as any local or domain user that is not currently signed in to the Windows asset. Now check the results. The code may be useful on its own but can really assist when scaling out PowerShell operations and the automation of tasks.
Now that you have the username, you may want to Get Logged-On User's Home Drive Location. If you do, please check out the linked post.
Thanks for reading,