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 = "alexd@MyTenant.onmicrosoft.com"
$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 = @("alexd@MyTenant.onmicrosoft.com","sarad@MyTenant.onmicrosoft.com","kevin@MyTenant.onmicrosoft.com")
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"
}}

Advertisements
Advertisements

No comments:

Post a Comment