Kae Travis

Use PowerShell to get the Current Username and Sid from an Elevated Session (Updated)

This post shows how to use PowerShell to get the current username and sid from an elevated session.

Typically speaking, if you were running powershell.exe as an elevated user and typed $env:USERNAME you would see the username of the elevated user – NOT the logged in user. The same principle would apply if you started querying the HKCU registry – you would be reading the current user registry for the elevated user, NOT the logged in user.

But there are times when we want to know who the logged in user is from an elevated account. We may also want to know the user sid so we can query HKEY_Users. Here’s a quick example of how we can use PowerShell to get the current username and sid from an elevated session:

$loggedInUser = Get-CimInstance –ClassName Win32_ComputerSystem | Select-Object @{Name = 'Username'; Expression = {$_.Username}}, @{Name = 'Sid'; Expression = {([System.Security.Principal.NTAccount]$_.UserName).Translate([System.Security.Principal.SecurityIdentifier]).Value}}
write-host "Username is: " $loggedInUser.Username
write-host "Sid is: " $loggedInUser.Sid

Update:

Sometimes the code above won’t work over an RDP session, in which case try the below instead.

$loggedInUser = (Get-WmiObject -Class Win32_Process | Where-Object {$_.ProcessName -eq "explorer.exe"}).GetOwner() | Select-Object -First 1 @{Name = 'Username'; Expression = {$_.User}}, @{Name = 'Sid'; Expression = {([System.Security.Principal.NTAccount]$_.User).Translate([System.Security.Principal.SecurityIdentifier]).Value}}
write-host "Username is: " $loggedInUser.Username 
write-host "Sid is: " $loggedInUser.Sid
Use PowerShell to get the Current Username and Sid from an Elevated Session
Use PowerShell to get the Current Username and Sid from an Elevated Session (Updated)

Leave a Reply