skip to Main Content

I needed to find a user based on their email address (to which they had received a license) and then connect that back to their primary identity for our internal billig.

In AD there are 2 fields that hold the emails:

  • email
  • proxyAddresses.*

How can I find the actual user’s identity based on any 1 of their email addresses

2

Answers


  1. Chosen as BEST ANSWER

    Finding a user by their primary email address is quite simple:

    # user based on primary email
    & az ad user list --query "[?mail=='$email'].userPrincipalName"
    

    Finding a user based on an email alias is a bit harder. In our case these are all stored in the proxyAddresses field in their user profile and the values are prefixed with smtp:. To find them use:

    # user based on alias
    & az ad user list --filter "proxyAddresses/any(p:p eq 'SMTP:$email')" --query "[].userPrincipalName"
    

  2. # Installed through the Gallery (one time only):
    Install-Module Microsoft.Graph -Scope CurrentUser
    
    Connect-MgGraph
    
    # query for `mail`
    Get-MgUser -Filter "mail eq '$email'"
    # query for `proxyAddresses`
    Get-MgUser -Filter "proxyAddresses/any(p:p eq 'SMTP:$email')"
    
    • Using Az:
    # Installed through the Gallery (one time only):
    Install-Module Az -Scope CurrentUser
    
    Connect-AzAccount
    
    # query for `mail`
    Get-AzADUser -Filter "mail eq '$email'"
    # query for `proxyAddresses`
    Get-AzADUser -Filter "proxyAddresses/any(p:p eq 'SMTP:$email')"
    

    If you want to go full vanilla and query the user API directly you will need an application with one of these Permissions then the code to request a token and query the API would be (notice variables that should be pre-populated: $appid, $secret, $tenantId, $email):

    $params = @{
        Uri    = "https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token"
        Method = 'POST'
        Body   = @{
            Grant_Type    = 'client_credentials'
            Scope         = 'https://graph.microsoft.com/.default'
            Client_Id     = $appid
            Client_Secret = $secret
        }
    }
    $token = Invoke-RestMethod @params
    
    
    $request = @{
        Uri     = "https://graph.microsoft.com/v1.0/users?`$filter=mail eq '$email'"
        Headers = @{
            Authorization = $token.token_type + ' ' + $token.access_token
        }
    }
    (Invoke-RestMethod @request).value
    
    $request = @{
        Uri     = "https://graph.microsoft.com/v1.0/users?`$filter=proxyAddresses/any(p:p eq 'SMTP:$email')"
        Headers = @{
            Authorization = $token.token_type + ' ' + $token.access_token
        }
    }
    (Invoke-RestMethod @request).value
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search