Home > OS >  find UPN's from email address Powershell / AAD
find UPN's from email address Powershell / AAD

Time:06-12

Powershell noob here trying to get a list of UPN's from AAD using only a csv with email address and failing any help pointing me in the correct direction;

Example CSV extract

I can obtain the UPN from a single email address using this code;

$User = "[email protected]"

Get-AzureADUser -Filter "startswith(Mail,'$User')" | Select-Object DisplayName,UserPrincipalName,Mail,ObjectId | Export-csv -append -notypeinformation “C:\Temp\output.csv”

My attempt to do this for multiple email addresses in a csv fails here is what i have so far;

$Result = @()
 
$AllUsers = Import-Csv "C:\Temp\Users.csv"
 
ForEach ($User in $AllUsers)
{
    Get-AzureADUser -Filter "startswith(Mail,'$Users')" | Select-Object DisplayName,UserPrincipalName,Mail,ObjectId
 
$Result  = New-Object PSObject -property $([ordered]@{
UserName = $User.DisplayName
UserPrincipalName = $User.UserPrincipalName
PrimarySmtpAddress = $User.Mail
AliasSmtpAddresses = ($User.ProxyAddresses | Where-Object {$_ -clike 'smtp:*'} | ForEach-Object {$_ -replace 'smtp:',''}) -join ','
UserId= $User.ObjectId
})
}

$Result | Export-CSV "C:\Temp\output.csv" -NoTypeInformation -Encoding UTF8

any suggestions where i am failing in the above or recommendations on how to do this better?

CodePudding user response:

The main issue is in your filter, "startswith(Mail,'$Users')", in this case $Users is not defined.

Next issue is, Get-AzureADUser is being called but it's output is not being captured.

This should work, I'm assuming the Csv column having the user's emails is called EmailAddress, change (Import-Csv ...).EmailAddress for the corresponding property Name.

# for each value in the "EmailAddress" Column
(Import-Csv "C:\Temp\Users.csv").EmailAddress | ForEach-Object {
    # if the user exists in Azure AD
    if($azusr = Get-AzureADUser -Filter "mail eq '$_'") {
        # output this object
        [pscustomobject]@{
            UserName           = $azusr.DisplayName
            UserPrincipalName  = $azusr.UserPrincipalName
            PrimarySmtpAddress = $azusr.Mail
            AliasSmtpAddresses = $azusr.ProxyAddresses -clike 'smtp:*' -replace 'smtp:' -join ','
            UserId             = $azusr.ObjectId
        }
    }
 } | Export-CSV "C:\Temp\output.csv" -NoTypeInformation -Encoding UTF8
  • Related