I'm looking for a way to get the User Principal Name (UPN) from the currently logged-in user in a hybrid environment using PowerShell. I know the command `quser` gives me the SamAccountName of the active user, which I can parse, but I'm struggling to find a method to get the UPN directly. I understand there are options to retrieve it from Outlook or similar applications if the user is signed in, but I'm aiming to cover all possible scenarios. Any suggestions?
4 Answers
Here's a sneak peek from a previous inquiry: you can use this snippet:
`$SessionID = [System.Diagnostics.Process]::GetCurrentProcess().SessionId`
`$LoggedOnUser = Get-ItemProperty -Path "HKLM:SOFTWAREMicrosoftWindowsCurrentVersionAuthenticationLogonUISessionData$($SessionID)" -Name LoggedOnUser`
`Write-Host "I'm logged in with $($LoggedOnUser.LoggedOnUser)"`
This should help you get the logged-in user's details.
The UPN can be stored in a few registry locations, but it's not something you can count on being there consistently. Have you checked with `dsregcmd`? It might have the info you need.
If you're just after the UPN, why not get the SamAccountName first and then use it with the `Get-ADUser` cmdlet? It’s a straightforward approach, though it does require the AD PowerShell module to be installed.
You can open a command prompt or PowerShell in the user context and run `whoami /upn`. That should give you the UPN directly without needing to dig through other methods.

Related Questions
Can't Load PhpMyadmin On After Server Update
Redirect www to non-www in Apache Conf
How To Check If Your SSL Cert Is SHA 1
Windows TrackPad Gestures