SharePoint 2013 – Call Search REST API from PowerShell Script

Add-Type -AssemblyName System.Web

$sServerPath = “http://<Site URL>”
$sQueryOptions = “selectproperties=’ManagedPropertyName’&clienttype=’ContentSearchRegular’&QueryTemplatePropertiesUrl=’spfile://webroot/queryparametertemplate.xml'”
$sUserName = “user name”
$sPassword =”password”
$sDomain=”domain name”
$WebRMethod=[Microsoft.PowerShell.Commands.WebRequestMethod]::Get

function Get-SPSearchResults
{
param ($keyword,$sUserName,$sPassword, $sDomain, $WebRMethod)
try
{
$spCredentials = New-Object System.Net.NetworkCredential($sUserName,$sPassword,$sDomain)
$enckeyword = [System.Web.HttpUtility]::UrlEncode(“‘$keyword'”)
$url = $sServerPath+”/_api/search/query?querytext=$enckeyword”+”&$sQueryOptions”

$spWebRequest = [System.Net.WebRequest]::Create($url)
$spWebRequest.Credentials = $spCredentials
$spWebRequest.Accept = “application/json;odata=verbose”
$spWebRequest.Method=$WebRMethod
$spWebResponse = $spWebRequest.GetResponse()
$spRequestStream = $spWebResponse.GetResponseStream()
$spReadStream = New-Object System.IO.StreamReader $spRequestStream
$spData=$spReadStream.ReadToEnd()
$results = $spData | ConvertFrom-Json
$results = $results.d.query.PrimaryQueryResult.RelevantResults.Table.Rows.results

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 ‘Title’)
{
Write-Host $row.Cells.results[$j].Value -ForegroundColor Green
}
}
}
}
catch
{
Write-Host $_.Exception.Message -ForegroundColor Red
}
}

try
{
Get-SPSearchResults -keyword “ca” -sUserName $sUserName -sPassword $sPassword -sDomain $sDomain -WebRMethod $WebRMethod
}
catch
{
Write-Host “Problem in running the REST API. Failed with error : ” + $_.Exception.Message -ForegroundColor Red
}

Advertisements

About Joseph Velliah
As a SharePoint Developer my professional interests tend to be technical and SharePoint focused. I run a blog at "SP RIDER" where you can expect to read HOW TOs and scenarios that I run into during my day to day job. I hope my posts will give back a little to the community that is helped me.

Comments are closed.

%d bloggers like this: