Office 365/Sharepoint Online - PowerShell Script To Call Search API And Get The Result

Our client has an Office 365 tenant and is very heavily using SharePoint online. We have one big SharePoint online site collection. Site collection has lots of content and there is also unwanted content available. The customer wants to clean up the site collection. Customer requested to get all the items/documents which are not updated since last year. Customer also wants the view count / open count for respective list items and documents.

One thought came to mind, that is - Audit Reports which we were supposed to use in the On Premises version. So we went to Site Settings >> Site Collection Administration >> Audit log reports (https://myTenant/_layouts/15/Reporting.aspx?Category=Auditing)

But in SharePoint online Audit log reports don't works, it says, even though Auditing is enabled.

Figure 1 : SharePoint Online : Audit Log Report

These audit reports never worked for us in SharePoint online. So, the option remains of  using Search and managing meta data property “ViewsLifeTime” and “ViewsLifeTimeUniqueUsers”. We configured the Content Search webpart and could see the result for some data. For some data these properties didn’t return any result.

Our customer wants the result in excel sheet and its really difficult to get content search Web Part result in excel sheet though we can write from display template.

Finally, we decided to write the PowerShell script and call the search APIs like KeywordQuery from the PowerShell script.

Here, I’ll explain step by step how to call search APIs from PowerShell script.

Step 1

Load the required libraries

  1. # add references to SharePoint client assemblies and authenticate to Office 365 site - required for CSOM    
  2. Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"    
  3. Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"    
  4. Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Search.dll"   
Step 2

Set the required variables like root SiteCollection URL, tenant admin UserName, and Password of your site to connect.
  1. #Specify tenant admin and URL  
  2. $User = ""    
  3. #Configure Site URL and User  
  4. $SiteURL = ""   
  5. #Password  
  6. $Password =" "    
  7. $securePassword = ConvertTo-SecureString -String $Password -AsPlainText –Force   
  8. $Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$securePassword)  
Step 3

Get the Microsoft.SharePoint.Client.ClientContext instance and set the credentials.
  1. #client context object and setting the credentials   
  2. $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)  
  3. $Context.Credentials = $Creds  
Step 4

Creating instance of KeywordQuery class and setting, selecting the properties.
  1. #Calling Search API - Create the instance of KeywordQuery and set the properties  
  2. $keywordQuery = New-Object Microsoft.SharePoint.Client.Search.Query.KeywordQuery($Context)   
  3. #Sample Query - To get the last year result  
  4. $queryText="Path:https://MySitePath/ AND LastModifiedTime<2015-11-05 AND Created<2015-11-05"  
  5. $keywordQuery.QueryText = $queryText  
  6. $keywordQuery.RowLimit=500  
  7. $keywordQuery.TrimDuplicates=$false  
  8. $keywordQuery.SelectProperties.Add("LastModifiedTime")  
  9. $keywordQuery.SelectProperties.Add("ViewsLifeTime")  
  10. $keywordQuery.SelectProperties.Add("ModifiedBy")  
  11. $keywordQuery.SelectProperties.Add("ViewsLifeTimeUniqueUsers")  
  12. $keywordQuery.SelectProperties.Add("Created")  
  13. $keywordQuery.SelectProperties.Add("CreatedBy")  
  14. $keywordQuery.SortList.Add("ViewsLifeTime","Asc")   
Step 5

Creating instance of SearchExecutor class and getting the result.
  1. #Search API - Create the instance of SearchExecutor and get the result  
  2. $searchExecutor = New-Object Microsoft.SharePoint.Client.Search.Query.SearchExecutor($Context)  
  3. $results = $searchExecutor.ExecuteQuery($keywordQuery)  
  4. $Context.ExecuteQuery()  
  5. #Result Count  
  6. Write-Host $results.Value[0].ResultRows.Count   
Step 6

Writing result to CSV file.
  1. #CSV file location, to store the result  
  2. $exportlocation = "G:\MCH\MCHS Marketing Team details\Admin_ViewsCount.csv"  
  3. foreach($result in $results.Value[0].ResultRows)  
  4. {  
  5. $outputline='"'+$result["Title"]+'"'+","+'"'+$result["Path"]+'"'+","+$result["ViewsLifeTime"]+","+$result["ViewsLifeTimeUniqueUsers"]+","+$result["CreatedBy"]+","+$result["Created"]+","+$result["ModifiedBy"]+","+$result["LastModifiedTime"]  
  7. Add-Content $exportlocation $outputline   
  8. }