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
The EnsureUser method in PowerShell is used to ensure that a specific user account exists in a SharePoint Online site collection. If the specified user account doesn’t exist, the method creates a new user account with the specified email address or username, without granting any permissions.
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 = "Salaudeen@crescent.com"
#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.
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 = "steve@crescent.com"
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
}
In summary, the EnsureUser method in PowerShell is a tool for checking if the specific user account exists in SharePoint Online site collections. By using this method, you can validate and add the specific user account to the site collection, if it doesn’t exists.
Here is another post to check if a user exists in SharePoint Online: PowerShell to check if a user exists in SharePoint Online