Kae Travis

Find the Current Logged On Username From a System Context

Posted on by in PowerShell

Sometimes we need to find the current logged on username from a system context. For example, consider I have the following two domain user accounts:

alkaneuser (standard permissions)

alkaneadmin (administrator permissions)

If I log into the machine as alkaneuser, and then elevate a PowerShell prompt as alkaneadmin and run:

write-host $env:username

You will notice that the output is alkaneadmin. Of course, what we’re trying to do here is ascertain the username of the logged in user (alkaneuser), and not the user running the current powershell process (alkaneadmin)!

To do this we can use the following script:

$usernamewithdomain = Get-WMIObject -class Win32_ComputerSystem | select -ExpandProperty username
$usernamewithoutdomain = $usernamewithdomain.split("\")[1]
write-host $usernamewithdomain
write-host $usernamewithoutdomain
Find the Current Logged On Username From a System Context
Find the Current Logged On Username From a System Context

Leave a Reply