jeezY
jeezY

Reputation: 21

Generate list of Azure AD email addresses from FirstName and LastName

I have a CSV file with two columns, firstname and lastname, which I'm trying to obtain the email addresses for. How would I go about creating a Powershell script which will run through the list and extract the email address of the person from Azure AD? I thought the following code would work but it seems I'm getting an error.

Import-Csv -Path "C:\path\to\file.csv" | ForEach-Object {
    $firstName = $_.FirstName
    $lastName = $_.LastName
    $user = Get-AzureADUser -Filter "startswith(givenName,'$firstName') and surname eq '$lastName'"
    if ($user) {
        Write-Output "$($user.UserPrincipalName)"
    }
}

Error:

Get-AzureADUser : Error occurred while executing GetUsers 
Code: Request_UnsupportedQuery
Message: Unsupported or invalid query filter clause specified for property 'givenName' 
of resource 'User'.
RequestId: 6da6daf9-2a2f-4f91-80e0-de152a2d7a62
DateTimeStamp: Thu, 07 Dec 2023 23:09:52 GMT
HttpStatusCode: BadRequest
HttpStatusDescription: Bad Request
HttpResponseStatus: Completed
At line:5 char:13
+     $user = Get-AzureADUser -Filter "startswith(givenName,'$firstName ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-AzureADUser], ApiException
    + FullyQualifiedErrorId : Microsoft.Open.AzureAD16.Client.ApiException,Microsoft.Op 
   en.AzureAD16.PowerShell.GetUser

Upvotes: 0

Views: 970

Answers (1)

Rukmini
Rukmini

Reputation: 15554

My CSV file looks like below:

enter image description here

To fetch the User Principal Names of the users, make use of below PowerShell script:

Connect-AzureAD

Import-Csv -Path "C:\Users\rukmini\Downloads\AzureADUPN.csv" | ForEach-Object {
    $firstName = $_.FirstName
    $lastName = $_.LastName

    # Remove leading and trailing spaces from names
    $firstName = $firstName.Trim()
    $lastName = $lastName.Trim()

   $filter = "givenName eq '$firstName' and surname eq '$lastName'"

    try {
        $user = Get-AzureADUser -Filter $filter -ErrorAction Stop
        Write-Output "$($user.UserPrincipalName)"
    } catch {
        Write-Output "User not found for $firstName $lastName"
    }
}

Output:

[email protected]
[email protected]
[email protected]

enter image description here

Upvotes: 1

Related Questions