Consume the SharePoint Query OM from PowerShell

In my previous post I mentioned that you can use the same search object models and interfaces to query both FAST Search and SharePoint Search in SharePoint 2010. So let's look at how you can accomplish this by issuing a simple query using PowerShell. 

First, start a PowerShell window by running "SharePoint 2010 Management Console" located in your Microsoft SharePoint 2010 Products folder on the start menu. This will automatically load the Microsoft.SharePoint.PowerShell snap-in so you can access SharePoint PowerShell commands. You can also access the Query OM classes from this PowerShell window, and the script below shows a simple example of how you can issue a query using the KeywordQuery class:

# setup a keyword query object

$site = New-Object Microsoft.SharePoint.SPSite "https://localhost"

$kq = New-Object Microsoft.office.Server.Search.Query.KeywordQuery $site

# set some query properties...

$kq.ResultTypes = [Microsoft.Office.Server.Search.Query.ResultType]::RelevantResults

$kq.RowLimit = 5

$kq.QueryText = "microsoft"

# issue the query...

$resultTableCollection = $kq.Execute()

# get the result table...

$relResultTable = $resultTableCollection.Item([Microsoft.Office.Server.Search.Query.ResultType]::RelevantResults)

$relDataTable = $relResultTable.Table

# and output the results

$relDataTable.Rows | Format-Table -AutoSize -Property Url,Title

As you can see, there is no explicit reference to which search provider (SharePoint Search or FAST Search) to use in this script. This means that the default provider on the Search Service Application (see architecture overview) will be used. So the same script can be run, regardless of search provider, to get search results..

If you want, you can explicitly set the provider. This is done by setting the ResultsProvider property on the KeywordQuery object before executing the query.

$kq.ResultsProvider = [Microsoft.Office.Server.Search.Query.SearchProvider]::FASTSearch

The Query OM provides a unified interface for querying both SharePoint Search and FAST search, while PowerShell provides a quick and easy way of accessing the OM. Simple scripting in Powershell can be useful in several cases, e.g. to

  • Test different query features. Create e.g. a script that queries with and witouht stemming, and compare results. 
  • Test and validate query setup. To see e.g. if you configured your Search Service Application correctly for FAST Search, set the result provider to FASTSearch and issue a query. If setup is incomplete, you will see an exception