.net-corepowershell-core

How do you obtain the Active Directory email address of the current logged in user in PowerShell Core?


I've seen other questions/answers here that show how to do this in Windows PowerShell, and they work in Windows PowerShell, but not in PowerShell 6+, i.e., PowerShell Core, which is built on top of .NET Core.

How do I get the Active Directory email address of the domain-joined current user in PowerShell Core?

If they are not AD-domain joined, it doesn't matter what it does (throws an error, returns an empty string, whatever).

Thanks!

I've looked into the example here: How to obtain email of the logged in user in powershell, but the "[adsi]" types are not available.

I've considered "$env:username@$env:userdnsdomain", but that gives incorrect results.

Thanks!

Note: this is in Windows (Windows 10, specifically). I need the user's email address in order to generate an auth token with ADAL. It can do it without the user's email address in .NET, but not in .NET Core.

For example, I've got a user whose login is m8345. His email address could be "mike@somedomain.com" or "mike@otherdomain.com" or "mike@ntdev.somedomain.com" or "mike.smith@somedomain.com", etc., i.e., there's not necessarily any correlation between the logon name (i.e., "%username%") and the email address... yet .NET can resolve it, but .NET core cannot.


Solution

  • After much tribulation, I figured it out:

    ([ADSI]"LDAP://<SID=$([Security.Principal.WindowsIdentity]::GetCurrent().User.Value)>").UserPrincipalName