SharePoint Online: Find All Documents using Keyword Query PowerShell

Requirement: Get All Documents in SharePoint Online Site and Export to CSV

PowerShell to Find All Documents using Keyword Query in SharePoint Online

A user wants to get a list of all documents which are not been updated in recent years. So, Here is the PowerShell script to get all documents in a SharePoint Online site collection sorted by “Last modified Date”.

#Load SharePoint CSOM Assemblies
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"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Search.dll"

#Config Variables
$SearchQuery= "path: AND IsDocument:true AND (NOT FileType:aspx)"
$CSVFile = "C:\Temp\SearchResults.csv"

Try {
    $Cred= Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
    #Define Keyword
    $KeywordQuery = New-Object Microsoft.SharePoint.Client.Search.Query.KeywordQuery($Ctx)
    $KeywordQuery.QueryText = $SearchQuery
    $KeywordQuery.RowLimit  = 500

    #Execute Search        
    $SearchExecutor = New-Object Microsoft.SharePoint.Client.Search.Query.SearchExecutor($Ctx)
    $SearchResults = $SearchExecutor.ExecuteQuery($KeywordQuery)

    Write-host "Search Results Found:"$SearchResults.Value[0].ResultRows.Count

    #Get Search Results
        $Results = @()
        foreach($Result in $SearchResults.Value[0].ResultRows)
            $Results += New-Object PSObject -Property @{
                        'Document Name' =  $Result["Title"]
                        'URL' = $Result["Path"]
                        'Created By' = $Result["CreatedBy"]  
                        'Last Modified' = $Result["LastModifiedTime"]               
        #Export search results to CSV
        $Results | Export-Csv $CSVFile -NoTypeInformation
        Write-Host -f Green "Search Results Exported to CSV File!"
Catch {
    write-host -f Red "Error Getting Search Results!" $_.Exception.Message


keyword query language sharepoint online

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

Your email address will not be published. Required fields are marked *