Fetching Group And User Information In SharePoint Online Site Using PowerShell CSOM

Client side object model is becoming very popular now and learning CSOM is mandatory to access the various resources present in SharePoint Online.

In today’s blog, I will explain how to fetch the groups and users in a site collection that is residing in office 365. We are using CSOM PowerShell scripting to get all the required information. 

Hence, let’s get started.

In order to execute this script, we require two important DLL’s (dynamic link library) namely Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.RunTime, so we are using add-type path to load the two DLLs. This is used to add a .NET Framework type of the class to the execute PowerShell session and clear-host will remove any messages in the console Window of Windows PowerShell.

Clear-Host

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"


In the next step, we are declaring a $credential variable to fetch the credentials to access SharePoint Online. This will prompt the user to enter the username and password and the password that we get is converted into the secured string. For security reasons, $url is required to put appropriate SharePoint online URL.

  1. $credential=Get-Credential  
  2. $ctx=""  
  3. $username=$credential.UserName  
  4. $password=$credential.GetNetworkCredential().Password  
  5. $securepassword=ConvertTo-SecureString $password -AsPlainText -Force  
  6. $url="your site collection url"  
Now, we are writing a function to fetch the required details. We are including the code block inside try and catch, as it is a best coding practice. We are getting context of Sharepoint Online site, using ClientContext Object. By passing URL, we are setting the credentials to SharePointOnlineCredentails Object by passing the username and secured password. Now, $web will get root site. $ctx.load will load the $web object in to the client context and we are getting SiteGroups, SiteUsers from the $web and loading it in to the client context. Use context.executequery() to complete the load action to get all the site groups in a variable of type GroupCollection Object.
  1. try {  
  2.   
  3.     function GetSourceGroupsandUsers() {  
  4.         $grouparray = @()  
  5.         $ctx = New - Object Microsoft.SharePoint.Client.ClientContext($url)  
  6.         $Credentials = New - Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securepassword)  
  7.         $ctx.Credentials = $Credentials  
  8.         $web = $ctx.Web  
  9.         $ctx.Load($web)  
  10.         Write - Host $web.Title  
  11.         $ctx.Load($web.SiteGroups)  
  12.         $ctx.Load($web.SiteUsers)  
  13.         $ctx.ExecuteQuery()[Microsoft.SharePoint.Client.GroupCollection] $groupcollection = $web.SiteGroups  
Now, we are iterating through each group and loading it. By fetching all the users for the group and for each of the users in a group, we are fetching the login name, group name, group Id and user name. This information is collected through PS Object with various members (PSObject is similar to any other object and members are similar to properties of an object) and finally we are adding each object to $grouparray variable. Afterwards, we are using export-csv cmdlet, which will convert the array of the objects to a CSV file and path is where CSV file is saved. 
  1. foreach($group in $groupcollection) {  
  2.     $ctx.Load($group)  
  3.     $ctx.ExecuteQuery()  
  4.     $siteusers = $group.Users  
  5.     $ctx.Load($siteusers)  
  6.     $ctx.ExecuteQuery()  
  7.     foreach($user in $siteusers) {  
  8.         $obj = New - Object PSObject  
  9.         $login = $user.LoginName  
  10.         $obj | Add - Member - MemberType NoteProperty - Name "LoginName"  
  11.         $login  
  12.         $obj | Add - Member - MemberType NoteProperty - Name "Group Name"  
  13.         $group.Title  
  14.         $obj | Add - Member - MemberType NoteProperty - Name "Group Id"  
  15.         $group.Id  
  16.         $obj | Add - Member - MemberType NoteProperty - Name "User Name"  
  17.         $user.Title  
  18.         $grouparray += $obj  
  19.     }  
  20. }  
  21. $grouparray | Export - Csv - Path "your export path"  
  22. }  
We are calling the function GetSourceGroupsandUsers and finally ending the code try block with catch block. Any error message can be logged in, using out-file and provide the path to save the log file. 
  1. GetSourceGroupsandUsers  
  2. }  
  3. Catch {  
  4.     $errormessage = $_.Exception.Message  
  5.     $errormessage | Out - File "your path for exception logging"  
  6.     Write - Host "Some Error Occurred"  
  7. }  
Note

To execute this script, one should have the site collection administrator access for the site. Please find the attached script for the reference and the same can be downloaded.