Contents

Get SharePoint site policies using PowerShell

 

Site Policies in SharePoint can be used to have a better governance as the platform is growing. Storage is expensive, so if you let your (unused) sites just “sitting there“, then it’s not a good use of money is it?

If you need more information about Site Policies, start with an Overview of site policies in SharePoint Server.

In this blog post, we are going to use PnP PowerShell to retrieve site policies that are applied in SharePoint Online site collections.
 

Create the PowerShell script

With PnP PowerShell, we use the Get-PnPSitePolicy to retrieve the policies applied to a site collection. BUT, we also need a list of the Site Collections don’t we? 😉 So we’ll also need to use the Get-PnPTenantSite cmdlet.

We will create an array (called $Results), and loop through each Site Collection while using the Get-PnPSitePolicy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$Results = @()
$AllSC = Get-PnPTenantSite

foreach ($SC in $AllSC){
    Write-Host "Connecting to" $SC.Url -ForegroundColor Green
      
    Connect-PnPOnline -Url ($SC).Url -Credentials $creds    
    $Policy = Get-PnPSitePolicy
    $SCProps = @{
        Url = $SC.Url
        Name = $Policy.Name
        Description = $Policy.Description
    }
    $Results += New-Object PSObject -Property $SCProps
} 
$Results | Select-Object Url, Name, Description

When we run the script, it works fine. However, what happens if there’s a Site Collection you do not have access to? 🤔 Well… We have a lovely red message on the console with error 401. And personally, I don’t like to see a bunch of red lines on my console!
 

Add error handling

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$Results = @()
$AllSC = Get-PnPTenantSite

foreach ($SC in $AllSC){
    Write-Host "Connecting to" $SC.Url -ForegroundColor Green
    Try{    
        Connect-PnPOnline -Url ($SC).Url -Credentials $creds -ErrorAction Stop
        $Policy = Get-PnPSitePolicy
        $SCProps = @{
            Url = $SC.Url
            Name = $Policy.Name
            Description = $Policy.Description
        }
        $Results += New-Object PSObject -Property $SCProps
    } 
    catch {
        Write-Host "You don't have access to this Site Collection" -ForegroundColor Red
    }
    
} #end foreach
$Results | Select-Object Url, Name, Description

 

Run the script

Should we have a look at the results? Yes! Save the script in your location of choice, and let’s run it. Error handling is already much better!

/images/powershell-screenshots/get-site-policies-img1.png