Call Search Rest API with PowerShell
Use SharePointPnPPowerShell module
I want to perform a quick test of search setting for my SP Online. There are many samples demonstrate how to do it with your code but not much for PowerShell. Why not? As a SharePoint admin, you should not require to write an webpart or download an open source tool for test purpose.
For a Windows 10 PC, you have PowerShell ISE built-in. You will also need 2 modules:
- SharePoint Online Management Shell
- SharePointPnPPowerShell (run Install-Module SharePointPnPPowerShellOnline in PowerShell to install it)
Here is my script for your reference. The script is searching keyword “abc” and return only files from OneDrive:
Add-Type -Path “C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.dll”
Add-Type -Path “C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.SharePoint.Client.Runtime.dll”
Add-Type -Path “C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.Online.SharePoint.Client.Tenant.dll”
# Connect to SharePoint Online
$targetSite = “https://[tenantname].sharepoint.com"
$targetSiteUri = [System.Uri]$targetSite
$keyword = “abc”
$filetype = “docx”
#$sQueryOptions = “refiners=’filetype’&refinementfilters=’filetype:equals(`”$filetype`”)’”
$sQueryOptions = “refiners=’Path’&refinementfilters=’(Path:%22https://[tenantname].sharepoint.com/personal*%22)'"
$username = “[your SPO username]”
$credentials = Get-Credential -UserName $username -Message “Please enter password for $username”
Connect-PnPOnline -Credentials $credentials -Url $targetSite
$context = (Get-PnPWeb).Context
$credentials = $context.Credentials
$authenticationCookies = $credentials.GetAuthenticationCookie($targetSiteUri, $true)
# Set the Authentication Cookies and the Accept HTTP Header
$webSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$webSession.Cookies.SetCookies($targetSiteUri, $authenticationCookies)
$webSession.Headers.Add(“Accept”, “application/json;odata=verbose”)
# Set query string
$apiUrl = “$targetSite” + “/_api/search/query?querytext=`’$keyword`’”+”&$sQueryOptions”
# Make the REST request
$webRequest = Invoke-WebRequest -Uri $apiUrl -Method Get -WebSession $webSession
# Consume the JSON result
$json = $webRequest.Content | ConvertFrom-Json
$results = $json.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results
if ($results.count -gt 0){
for($i=0; $i -le $results.length-1; $i++) {
$row = $results[$i];
for ($j=0; $j -le $row.Cells.results.length-1; $j++) {
if ($row.Cells.results[$j].Key -eq ‘Path’) {
Write-Host $row.Cells.results[$j].Value -ForegroundColor Cyan
}
}
}
}
else
{
write-host “No result”
}