Check if Azure AD Users exists PowerShell function

The estimated reading time 4 minutes

When scripting with cloud users in AzureAD some people might ask how to check if an Azure AD user is available or not. I also had to challenge this scenario while scripting for a customer. After this I thought this is something many people may need. So here is my solution with some explanation to use it in your own script.

Checking an normal Azure AD User

Function Check-AzureUser()
{
  param(
    [Parameter(Mandatory=$true)][string]$UserPrincipalName
 )
  ## check if azure AD connection is already established (if not quit function)
        try {
            Write-Host "Checking if Azure AD Connection is established..." -ForegroundColor Yellow
            $azconnect = Get-AzureADTenantDetail -ErrorAction Stop
            $displayname = ($azconnect).DisplayName
            write-host "Azure AD connection established to Tenant: $displayname " -ForegroundColor Green
            }
            catch {
            write-host "No connection to Azure AD was found. Please use Connect-AzureAD command" -ForegroundColor Red
            break
                    }
                    ## check if user exists in azure ad 
                    #check if upn is not empty    
                    if($UserPrincipalName){
                    $UserPrincipalName = $UserPrincipalName.ToString()
                    $azureaduser = Get-AzureADUser -All $true | Where-Object {$_.Userprincipalname -eq "$UserPrincipalName"}
                       #check if something found    
                       if($azureaduser){
                             Write-Host "User: $UserPrincipalName was found in $displayname AzureAD." -ForegroundColor Green
                             return $true
                             }
                             else{
                             Write-Host "User $UserPrincipalName was not found in $displayname Azure AD " -ForegroundColor Red
                             return $false
                             }
                    }
}

What does this small function?

  1. It checks if there is a connection to azure AD, if not function is canceled (line 8 -17)
  2. Get’s all Azure AD users and searches for the userprincipalname it was given as parameter
  3. If a user was found it returns a “TRUE”, if not a “FALSE”

So how can you use this? Well it’s quite easy. Execute the complete function and then type;

Check-AzureUser emailadd@domain.com

$user = "userexists@it-koehler.com"

if(Check-AzureUser $user){
 Write-Host "Do something with this user $user.." -ForegroundColor Green
}
else{
    Write-Host "Break the script" -ForegroundColor Red
}

The function return a “TRUE” if the user exists, so it can be used in an IF case. As shown in the example.

Checking an Azure AD Guest User

Sometimes people want to check if special guest users exists and so some things with them (may inviting to teams anything else inside the M365 Tenant), so I wrote another function to manage this kind of requirement.

Function Check-AzureGuestUser(){
  param(
    [Parameter(Mandatory=$true)][string]$Mailaddress
  )

  try {
    Write-Host "Checking if Azure AD Connection is established..." -ForegroundColor Yellow
    $azconnect = Get-AzureADTenantDetail -ErrorAction Stop
    $displayname = ($azconnect).DisplayName
    write-host "Azure AD connection established to Tenant: $displayname " -ForegroundColor Green
    }
    catch {
    write-host "No connection to Azure AD was found. Please use Connect-AzureAD command" -ForegroundColor Red
    break
            }
            $guestuser = Get-AzureADUser -Filter "userType eq 'Guest'" -All $true | Where-Object {$_.Mail -eq "$Mailaddress"}

            if($guestuser){
              $guestemail = ($guestuser).Mail
              $guestupn = ($guestuser).Userprincipalname
                    #check if something found    
                 
                       Write-Host "GuestUser: $guestupn was found in $displayname AzureAD." -ForegroundColor Green
                       return $true
             }
              else{
                Write-Host "User $UserPrincipalName was not found in $displayname Azure AD " -ForegroundColor Red
                return $false
                }
}

What does this function do? Nearly the same as the first one.

  1. Check the Azure AD connection
  2. Checks all guest users and if the user in parameters exists
  3. Finds the userprincipalname of the guest (with it’s mailaddresss)
  4. Returns “TRUE if the guest exists or “FALSE” if guest does not exist

Same procedere here:

Check-AzureGuestUser guest@gmail.com

Another small usecase.

$user = "guest@gmail.com"

if(Check-AzureGuestUser $user){
 Write-Host "Do something with this user $user.." -ForegroundColor Green
}
else{
    Write-Host "Break the script" -ForegroundColor Red
}

I think this not that complicated at all.

Combine all together

Sometimes you need to know whether a user exists and is a azure ad user or guest (specially if you have multiple Domains integrated)
You can use this two functions and put it together to check if an user (no matter guest or azure user exists). Have a look at the magic.


$azusers = "notexisting@it-koehler.com","existing@it-koehler.com","existguest@web.de","notexistguest@gmail.com"
foreach($azuser in $azusers ){
      if(Check-AzureUser -UserPrincipalName "$azuser"){
        Write-Host "$azuser is an AzureAD User" -ForegroundColor Green
       }
      else{
            if(Check-AzureGuestUser -Mailaddress "$azuser"){
              Write-Host "$azuser is a guest user"
            }
            else{
              Write-Host "User $azuser was not found in azure ad, checked azure ad user and guest user" -ForegroundColor Gray
            }
      }
}

This small piece of code checks if it is an azure AD user, if not it checks the mailadress for guest users. No user found in guest or azure ad user it says no user found. These two functions are not that difficult but can help to minimize errors while user creation.

If you liked this article please click on “Helpful”, otherwise please use the comment section and let me know.

Stay tuned and keep on azure scripting.

Was this article helpful?
YesNo
3.5 2 votes
Article Rating
Subscribe
Notify of
guest
9 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Fosh
Fosh
1 year ago

Hello – A very lovely article that works and which I find very useful. It does the job.
Just wondered if there is a way to expand on it to pull the list of users from a CSV using something like import-csv. I have tried to do this but getting errors.

Fosh
Fosh
Reply to  A.K.
1 year ago

Hi Alexander,

Thanks for the prompt response. I will try it and let you know how I get on.

Fosh
Fosh
Reply to  A.K.
1 year ago

I have just checked an my delimeter looks like this below:

Emailaddress,Firstname,Surname,Displayname
xlufxsh@gmail.com,xlu,Xsholomagba,Xlu Xsholomagba

Fosh
Fosh
Reply to  A.K.
1 year ago

Hi Alexander,

Thanks – It worked a trick – This is a great article and should be rated a 5. I will like an opportunity to re-rate this article.

trackback
2 years ago

[…] Check if Azure AD Users exists PowerShell function – it … […]

trackback
2 years ago

[…] Check if Azure AD Users exists PowerShell function – it … […]

trackback
2 years ago

[…] Check if Azure AD Users exists PowerShell function – it … […]

trackback
3 years ago

[…] Check if Azure AD Users exists PowerShell function available first on […]