PowerShell script to check a list of users in AzureAD

DCA 0 Reputation points
2023-03-24T04:04:06.2066667+00:00

Hi,

I need a script that gets a list of users from a CSV file and then checks to see if they exist in AzureAD (Get-AzureADUser)?

Then exports it back out into another CSV file

PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,050 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,459 questions
{count} votes

1 answer

Sort by: Most helpful
  1. VenkateshDodda-MSFT 18,191 Reputation points Microsoft Employee
    2023-03-24T06:56:36.3666667+00:00

    @DCA Thank you for reaching out to Microsoft Q&A.

    Based on the shared information, we have understood you have csv file which contains all the user properties like (UserPrincipalName, objectId(id) etc.,) and you need to check whether those users are present under your Azure AD tenant or not by using PowerShell.

    I have written the below PowerShell Script which will import the user from csv (from your local Machine) and check whether user is present in Azure AD or not and then export to new csv file to your local machine.

    Connect-AzureAD
    $result=@()
    $csvobjectId= Import-Csv -Path <Csvfile_stored_InLocal> | select -ExpandProperty objectId 
    foreach( $item in $csvobjectId){
      $var=$(try{ Get-AzureADUser -ObjectId $item} catch {$null}) #condition to check user present or not
      if( $var -ne $null){
        $userExists=$true
      }
      else{
        $userExists=$false
      }
      $result += New-Object PSObject -Property @{ UserPrincipalName = $var.UserPrincipalName  
      UserExists = $UserExists 
      UobjectId= $item}
    }
    $result| Select UserobjectId,UserPrincipalName,UserExists| Export-Csv <path_of_newfile> -NoTypeInformation -Encoding UTF8
    
    

    In my local I have created a user.csv file which has three columns ( DisplayName,UserPrincipalName,ObjectId) and I have passed objectId to -ExpandProperty while importing the user list from local to PowerShell. User's image

    Note: Check whether your input csv file is storing the user object id with column name as id or objectId and make the necessary changes in line#3 in above shared script.

    Feel free to reach back to me if you have any further questions on this.

    0 comments No comments