Streamlining SharePoint Site and Group Data Extraction Using PnP PowerShell

Managing and auditing SharePoint sites often requires extracting information like site groups and pages across a hierarchy of subsites. Doing this manually can be cumbersome, but leveraging PnP PowerShell can simplify and automate the process. In this blog post, we explore a script to connect to a SharePoint site, fetch its groups, and recursively gather data about subsites and their pages, exporting the results to a CSV file for easy analysis.

What Does This Script Do?

The Script Breakdown

$SiteURL = Read-Host "Enter Site URL:"
$CSVFile = "C:\Temp\Sites.csv"
Try {
    Connect-PnPOnline -Url $SiteURL -Interactive
    Write-Host $SiteURL
    
    Get-PnPSiteGroup -Site $SiteURL
    Write-Host $groups
    $WebsCollection = Get-PnPSubWeb -Recurse
    $PagesDataColl = @()
    ForEach ($Web in $WebsCollection) {
        Write-Host $Web.Url
        Connect-PnPOnline -Url $Web.Url -Interactive
   }
   $PagesDataColl
   $PagesDataColl | Export-Csv -Path $CSVFile -NoTypeInformation
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Step-by-Step Guide

1. Prompt for the Site URL

The script begins by asking the user to provide the SharePoint site URL:

$SiteURL = Read-Host "Enter Site URL:"

2. Establish Connection

Using the PnP PowerShell module, the script connects to the specified site interactively:

Connect-PnPOnline -Url $SiteURL -Interactive

3. Fetch Groups

The Get-PnPSiteGroup command retrieves all the groups for the specified site:

Get-PnPSiteGroup -Site $SiteURL

4. Recursively Retrieve Subsites

The script uses Get-PnPSubWeb -Recurse to gather all subsites under the main site:

$WebsCollection = Get-PnPSubWeb -Recurse

5. Connect to Each Subsite

For each subsite retrieved, the script connects interactively:

ForEach ($Web in $WebsCollection) {
    Connect-PnPOnline -Url $Web.Url -Interactive
}

6. Export Data to CSV

The collected data is stored in an array and exported to a CSV file:

$PagesDataColl | Export-Csv -Path $CSVFile -NoTypeInformation

7. Error Handling

The script wraps its operations in a Try-Catch block to gracefully handle errors:

catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Use Case Scenarios

Customizing the Script

Conclusion

This PnP PowerShell script is a powerful tool for SharePoint administrators, simplifying the process of auditing and managing site data. By leveraging automation, it saves time and ensures accurate, comprehensive reporting.

Try this script in your SharePoint environment and let us know how it improves your workflows!

Note: Ensure you have the PnP PowerShell module installed and the necessary permissions to execute this script in your SharePoint environment.