SharePoint Online: PowerShell EnsureUser Method

What is “EnsureUser” method in SharePoint Online?
As its name suggests, ensure user method in SharePoint Online checks if the given user account is valid and then adds the user object to the “User Information List”. You may also use this method to obtain the User object from the given user name.

Ensure User in SharePoint Online using PowerShell

Here is an example PowerShell script for SharePoint Online 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 {    
        #write-host -f Red "Error:" $_.Exception.Message
        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

This script checks if the given user account is valid and returns “True” if the user account is valid, False otherwise.

If you are getting “The specified user could not be found” error in SharePoint Online, probably the given user ID doesn’t exist in the Azure AD of your SharePoint Online tenant!

EnsureUser Method in PnP PowerShell

While the above code can be converted to PnP PowerShell methods, Here is the cleaner way:

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$UserEmail = "[email protected]"

Try {
    #Connect to PnP Online
    Connect-PnPOnline $SiteURL -Interactive

    #Resolve the User
    $User = Get-PnPUser | Where-Object Email -eq $UserEmail
    If($User -eq $null) {        
        $User = New-PnPUser -LoginName $UserEmail
    }

    #Return the User Object
    $User
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

Leave a Reply