SharePoint  

Automate SharePoint Online Restricted Search with PowerShell

This guide outlines a PowerShell script that automates the following tasks.

  • Loads SharePoint site URLs from a CSV file
  • Connects to the SharePoint Admin Center using certificate-based authentication
  • Applies tenant-level search restrictions
  • Sets site-level restrictions on all listed sites

CSV File Format

The CSV file must contain only one column with the header SiteUrl.

SiteUrl

  • https://contoso.sharepoint.com/sites/HR
  • https://contoso.sharepoint.com/sites/Finance
  • https://contoso.sharepoint.com/sites/Legal

Save this file, for example, as: C:\Document Folder\File.csv

Required Configuration

Before running the script, update the following placeholders.

  • $AdminURL
  • -ClientId
  • -Tenant
  • -CertificatePath
  • -CertificatePassword

Ensure your Azure AD app and certificate setup is correct for app-only auth.

Script Walkthrough

Step 1. Import CSV

$sites = Import-Csv -Path $csvFilePath

Reads site URLs from the provided CSV. The script exits if it fails to load.

Step 2. Connect to SharePoint Admin Center

Connect-PnPOnline -Url $AdminURL -ClientId <Your-ClientId> -CertificatePath <Path-To-Certificate>

Uses secure certificate-based authentication to log into the admin center.

Step 3. Configure Tenant-Level Settings

Set-PnPTenantRestrictedSearchMode -Mode Enabled
Set-PnPTenant -EnableRestrictedAccessControl $true

Step 4. Apply Site-Level Restrictions

foreach ($site in $sites) {
    Connect-PnPOnline -Url $site.SiteUrl ...
    Set-PnPTenantSite -Identity $site.SiteUrl -RestrictContentOrgWideSearch $true
}

Step 5. Disconnect

Disconnect-PnPOnline

Benefits

  • Automated: Applies policies across multiple sites with one script
  • Secure: Uses app-only auth and certificates
  • Compliant: Follows Microsoft 365 best practices

Notes

  • Install the PnP PowerShell module: Install-Module -Name PnP.PowerShell
  • Run PowerShell as Administrator
  • Test with a few sites before mass deployment

Conclusion

This script is a powerful addition to the toolkit of SharePoint Online administrators. By automating tenant and site-level restrictions through a simple CSV file, you can maintain governance and compliance at scale with minimal effort.