SharePoint Online: PowerShell EnsureUser Method

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

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 return "True" if the user account is valid, False otherwise.
SharePoint Online: PowerShell EnsureUser Method SharePoint Online: PowerShell EnsureUser Method Reviewed by Salaudeen Rajack on September 04, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.