Get microsoft account username?

Hello, is it possible to get the microsoft account username (which is an email address) for the logged in user?

I can get the local username with $env:USERNAME but the microsoft account login username (email address) eludes me…

I have a few PCs at home with multiple user accounts on each that the wife and kids share - this variable in powershell would help me out with a logon script.



Not as far as I’m aware. That account isn’t actually a “login” that has a local security token; it’s an association some chunk of the OS maintains. You’d have to maintain a mapping of username=whatever.

Thanks. I will go with the username to email mapping then.

This email stuff is stored as shown below, but only if that is what is used for logon or later associated with a local account at some later time.

Even with this, you cannot get it for the logged on user, just all users that have ever logged on using one. So, unless you know the username part match the name part of the presented email info below, then you have to match this up manually by asking each person.

The reason is, you’d have to log on as that user to look at their stuff and if you are doing this already, well, what’s really the point.

Get-ChildItem Registry::HKEY_USERS\.DEFAULT\Software\Microsoft\IdentityCRL\StoredIdentities\ `
| select pschildname

Get-ChildItem Registry::HKEY_USERS\*\Software\Microsoft\IdentityCRL\UserExtendedProperties\* `
| select pschildname

This worked on my laptop - Windows 10 1709

$loggedIN = (Get-WMIObject Win32_ComputerSystem).UserName
$loggedInSid = (Get-WmiObject Win32_UserAccount | where { $_.Caption -eq $loggedIN }).Sid
$CredentialKey = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\Credential Providers" -Recurse | where { $_.PSChildName -eq $loggedInSid }
$userNameKey = $CredentialKey.PSParentPath,$loggedinSid,"UserNames" -join "\"
$emailAddress = (Get-Childitem $userNameKey).PSChildName
Write-Output "UserName      : $loggedIn"
Write-Output "Email Address : $emailAddress"

It can probably be made more efficient.