Export Search Results for entire Office365 tenant to CSV

I needed to perform a search of our entire tenant for a few key terms and then produce a CSV of all the search results. I was not able to find anything on the web which produced this result. The best thing I could find was a PowerShell script for searching a single site collection but we have over 6000 site collections.

A resource at Microsoft provided this excellent script and I’m now sharing it with all of you. Enjoy!

Notes:
1. You will want to edit lines 6 and 7 with your tenant URL and your desired search terms.
2. If you are using Multifactor Authentication (MFA), you will need to comment line 15 and un-comment line 16. This article explains what’s going on here.
3. Read the notes in the comments before lines 22 and 23 regarding the -All and -MaxResults parameters.

# This script executes a search against the SPO search engine and exports
# the results to a CSV file.  The exported CSV file will be added to the same 
# Directory as the script

# Script Input Parameters   
$url = "https://tenantname.sharepoint.com/"  
$keyword = "SSN"  
$currentTime = $(get-date).ToString("yyyyMMddHHmmss");  
$outputFilePath = ".\SearchResults-"+$currentTime+".csv"  
$credentials = Get-Credential 
 
## Connect to SharePoint Online site  
# However, if you're using Multifactor Authentication (MFA), you'll want to comment out this next line
# and un-comment the line with the -UseWebLogin parameter
Connect-PnPOnline -Url $url -Credentials $credentials  
#Connect-PnPOnline -Url $url -UseWebLogin  
 
# Executes an arbitrary search query against the SPO search index  
# Note below the option of using -MaxResults to limite the number of rows returned.  This line is currently commented out
# The other option is to use the -All parameter to return all results, this line is currently active.
# Make sure only one of these two lines are active.
# $results = Submit-PnPSearchQuery -Query $keyword -MaxResults 10  
$results = Submit-PnPSearchQuery -Query $keyword -All
 
## Add each row of the search result to the hash table  
$hashTable=@()  
foreach($resultRow in $results.ResultRows)  
{  
    $obj=New-Object PSObject  
    $resultRow.GetEnumerator()| ForEach-Object{ $obj | Add-Member Noteproperty $_.Key $_.Value}  
    $hashTable+=$obj;  
    $obj=$null;  
}  
 
## Export content of hashtable to CSV  
$hashtable | export-csv $outputFilePath -NoTypeInformation  
 
## Disconnect the context  
Disconnect-PnPOnline  

You cannot copy content of this page