I have the following Powershell CSOM code to add a user to a sharepoint online site.I am not trying to add him to any group, but to give him permission explicitly to the site.
However , I am getting the error : Exception calling "ExecuteQuery" with "0" argument(s): "Can not find the principal with id: 14."Can anyone tell me what I am doing wrong?
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"
$SiteURL = "https://robinroyrbn.sharepoint.com/sites/AnotherTeamSite"
$UserAccount="i:0#.f|membership|[email protected]"
$PermissionToAdd="Read"
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
Try {
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Cred
$User = $Ctx.Web.SiteUsers.GetByLoginName($UserAccount)
$RoleDefToAdd = $Ctx.web.RoleDefinitions.GetByName($PermissionToAdd)
$RoleAssignment = $Ctx.web.RoleAssignments.GetByPrincipal($User)
$RoleAssignment.RoleDefinitionBindings.Add($RoleDefToAdd)
$RoleAssignment.Update()
$Ctx.ExecuteQuery()
write-host -f Green "User updated Successfully!"
}
Catch {
write-host -f Red "Error adding User !" $_.Exception.Message
}