SharePoint Online: PowerShell to Check If User Exists
Requirement: SharePoint Online PowerShell to check if the user exists.
There are different cases where you may need to check if a user exists in the Office 365 tenant and here are my PowerShell scripts:
Option 1: Check If User Exists in the Tenant using Azure AD Cmdlet
We can use the Get-MsolUser cmdlet of Azure AD to check if a given user account is valid.
Option 2: SharePoint Online Ensure User method to Validate a user
Here is the native SharePoint method to validate a user using PowerShell: The "EnsureUser" method.
There are different cases where you may need to check if a user exists in the Office 365 tenant and here are my PowerShell scripts:
Option 1: Check If User Exists in the Tenant using Azure AD Cmdlet
We can use the Get-MsolUser cmdlet of Azure AD to check if a given user account is valid.
Import-Module MSOnline #User Account Variable $UserAccount = "[email protected]" Try { #Get Credentials to connect $Cred = Get-Credential #Connect to Azure AD Connect-MsolService -Credential $Cred #Function to check if a user account exists in the tenant Function Check-UserExists() { Param( [Parameter(Mandatory=$true)] [string]$UserID ) $User = Get-Msoluser -UserPrincipalName $UserID -Erroraction SilentlyContinue if ($User -ne $null) { Return $True } else { Return $False } } #Call the function to validate the user account Check-UserExists $UserAccount } Catch { write-host -f Red "Error:" $_.Exception.Message }
Option 2: SharePoint Online Ensure User method to Validate a user
Here is the native SharePoint method to validate a user using PowerShell: The "EnsureUser" method.
#Load SharePoint CSOM Assemblies Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll" Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll" #Function to check if a user account is valid Function Ensure-SPOUser() { Param( [Parameter(Mandatory=$true)] [string]$UserID, [Parameter(Mandatory=$true)] [string]$SiteURL ) Try { #Setup Credentials to connect $Cred = Get-Credential #Setup the context $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL) $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password) #ensure sharepoint online user $Web = $Ctx.Web $User=$web.EnsureUser($UserID) $Ctx.ExecuteQuery() Return $True } Catch { Return $False } } #Variables $SiteURL = "https://crescent.sharepoint.com/Sites/marketing" $UserID = "[email protected]" #Call the function to Check if the user account is valid Ensure-SPOUser -UserID $UserID -SiteURL $SiteURL
No comments:
Please Login and comment to get your questions answered!