How to deal with permissions in SharePoint using the Client Side Object Model and PowerShell

By Danielle Arad - December 28, 2014
2 min read

This time I am sharing a PowerShell script about how to get the list of all SharePoint Groups and all the users per group in a SharePoint site using the Client Side Object Model in a PowerShell script:


$host.Runspace.ThreadOptions = “ReuseThread”

#Definition of the function that gets all the SharePoint groups and Users per Group in a SharePoint site
function Get-SPAllSharePointUsersInGroups
param ($sSiteColUrl,$sUserName,$sDomain,$sPassword)
Write-Host “—————————————————————————-” -foregroundcolor Green
Write-Host “Getting all Groups in a SharePoint Site” -foregroundcolor Green
Write-Host “—————————————————————————-” -foregroundcolor Green

#Adding the Client OM Assemblies
Add-Type -Path “C:\Scripts PS2 Office 365\Microsoft.SharePoint.Client.dll”
Add-Type -Path “C:\Scripts PS2 Office 365\Microsoft.SharePoint.Client.Runtime.dll”

#SPO Client Object Model Context
$spCtx = New-Object Microsoft.SharePoint.Client.ClientContext($sSiteColUrl)
$spCredentials = New-Object System.Net.NetworkCredential($sUserName,$sPassword,$sDomain)
$spCtx.Credentials = $spCredentials

#Root Web Site
$spRootWebSite = $spCtx.Web
#Collecction of Sites under the Root Web Site
$spSites = $spRootWebSite.Webs

#Loading Operations

#We need to iterate through the $spGroups Object in order to get individual Group information
foreach($spGroup in $spGroups){
Write-Host “* ” $spGroup.Title

#Getting the users per group in the SPO Site
foreach($spUser in $spSiteUsers){
Write-Host ” -> User:” $spUser.Title ” – User ID:” $spUser.Id ” – User E-Mail:” $spUser.Email ” – User Login:” $spUser.LoginName

catch [System.Exception]
write-host -f red $_.Exception.ToString()

#Required Parameters
$sSiteColUrl = “http://<Site_Url>”
$sUserName = “<UserName>”
$sPassword =”<UserPassword>”

Get-SPAllSharePointUsersInGroups -sSiteColUrl $sSiteColUrl -sUserName $sUsername -sDomain $sDomain -sPassword $sPassword

As you can see, the script defines a function that uses the CSOM as the foundations to get all the users per SharePoint group in a SharePoint Online site. The function uses standard SPO objects (ClientContext, Web, SiteGroups, Users) to get all the users in all the SharePoint Groups in a SharePoint site. You can download the PowerShell script from the following download page in the Script Center Gallery in TechNet: How to get all the Users and Groups in a SharePoint Sites using CSOM.

Happy new year and happy CloudSharing!

You may also be interested in reading about:
CSOM SharePoint 2013