Search code examples
azurepowershellazure-active-directorypowershell-3.0

Retrieving users from Azure AD with Powershell and a csv file


I want to get users from azure stored in a csv file

This is what i have tried so far but i've got no results and yet no errors

Connect-AzureAD
$usercsv= Import-Csv -Path C:\Victor\csv.csv -Delimiter "," | Select-Object userPrincipalName
if ($usercsv){
    foreach($user in $usercsv){
        try{
            Get-AzureADUser -All $True | Where-Object {$_.userPrincipalName -like $user}
            return;
            }
        catch { 
            Write-Output "error"
            Write-Error $_.Exception.Message
            }
    }

}
else{
"No user data stored"
}

Solution

  • If the CSV actually has UserPrincipalNames this should give you at least some expected results:

    Connect-AzureAD
    $usercsv = Import-Csv -Path C:\Victor\csv.csv #  -Delimiter "," > Is default for this cmdlet
    foreach($user in $usercsv)
    {
        $upn = $user.UserPrincipalName.Trim()
        $azUser = Get-AzureADUser -Filter "userPrincipalName eq '$upn'"
    
        if(-not $azUser)
        {
            Write-Warning "$upn could not be found in AzureAD"
            continue
        }
    
        $azUser
    }