Skip to content

Instantly share code, notes, and snippets.

@vgrem
Created July 21, 2016 12:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgrem/7ef20dc56a77c9440fd6ebeae0619721 to your computer and use it in GitHub Desktop.
Save vgrem/7ef20dc56a77c9440fd6ebeae0619721 to your computer and use it in GitHub Desktop.
The example demonstrates how to retrieve users and groups for a Web object using SharePoint CSOM API
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 Get-Context([String]$WebUrl,$UserName,$Password) {
$context = New-Object Microsoft.SharePoint.Client.ClientContext($WebUrl)
$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName, $SecurePassword)
return $context
}
Function Get-WebUsers() {
param(
[Microsoft.SharePoint.Client.Web]$Web = $(throw "Please provide a Web")
)
$ctx = $Object.Context
$assignments = $context.Web.RoleAssignments
$context.Load($assignments)
$context.ExecuteQuery()
$members = @()
$assignments.GetEnumerator() | % {
$member = $context.Web.RoleAssignments.GetByPrincipalId($_.PrincipalId).Member
$context.Load($member)
$members += $member
}
$context.ExecuteQuery()
$users = @()
$members | % {
if($_.PrincipalType -eq [Microsoft.SharePoint.Client.Utilities.PrincipalType]::User) {
$users += $_
}
}
$users
}
$Url = "https://contoso.sharepoint.com/news"
$Username = "jdoe@consoto.onmicrosoft.com"
$Password = ""
$context = Get-Context -WebUrl $Url -UserName $Username -Password $Password
#Reterieve web groups
$groups = $context.Web.RoleAssignments.Groups
$context.Load($groups)
$context.ExecuteQuery()
write "Group names:"
$groups.GetEnumerator() | % {
$_.Title
}
#Retieve web users
$users = Get-WebUsers -Web $context.Web
write "User names:"
$users | % {
$_.Title
}
$context.Dispose()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment