Friday, 11 November 2016

Check if Office 365 user exists or not with Powershell

In this article I am going write powershell script to check if an Office 365 user exists or not with the Azure AD Powershell cmdlet Get-MsolUser. First run the below command to connect Office 365 Powershell module.
Import-Module MSOnline
$msolCred = Get-Credential
Connect-MsolService –Credential $msolCred
The below command checks if the given user account already exists in Office 365 or not. You can retrieve user by using ObjectId or UserPrincipalName of the user.
$upn = ""
$User = Get-MsolUser -UserPrincipalName $upn -ErrorAction SilentlyContinue
If ($User -ne $Null) { 
"User exists in Azure AD" 
} Else {
"User not found in Azure AD"}
You need to use the parameter -ErrorAction SilentlyContinue to skip error when user not found, otherwise you will get the error message 'Get-MsolUser : User Not Found'.

Check if multiple Azure AD accounts are exists or not

First set list of user's userprincipalname as array object and enumerate the array to find user account in Office 365.
$users = @("","","")
foreach ($user in $users) {
$userobj = Get-MsolUser -UserPrincipalName $user -ErrorAction SilentlyContinue
If ($userobj -ne $Null) {
    Write-Host "$user already exists" -foregroundcolor "green"
} else {
    Write-Host "$user not found " -foregroundcolor "red"

Check if user in a CSV file exists in Azure AD

The below command imports user accounts from CSV file and check every user exist in Azure AD or not. Consider the CSV file Users.csv which includes the column UserPrincipalName which holds the UPN of user in each row of the csv file.
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = $_."UserPrincipalName"
$userobj = Get-MsolUser -UserPrincipalName $user -ErrorAction SilentlyContinue
If ($userobj -ne $Null) {
$UserExists = $true
} else {
$UserExists = $false
$Result += New-Object PSObject -property @{ 
UserPrincipalName = $user
UserExists = $UserExists }
$Result | Select UserPrincipalName,UserExists
Run the below command to export the result to CSV file.
$Result | Export-CSV "C:\\AccountStatusReport.csv" -NoTypeInformation -Encoding UTF8



  1. How can i have a .csv import in this?

    $users = Import-CSV "C:\temp\users1.csv"

    1. Hi, I have updated the post to check if user in CSV exists or not in Office 365