Partilhar via


Sharepoint search, powershell and keywordquery

Ever wanted to just query the search catalog for some text and get back your results without going into the browser?

Ever needed to use a sharepoint query to drive data through another script or other code?

Well, here's your answer. :)

I whipped this little widget up to use the KeywordQuery class to issue queries to a site and saves off the results as a CSV file.

Things to remember: Use the Microsoft.Office.Server.Search.Query.KeywordQuery class to do your dirty work, not Microsoft.SharePoint.Search.Query.KeywordQuery unless (I believe) you are using WSS 3.0 or SharePoint Foundation Server 2010 only.

And here you go - just save that off as .ps1 and run it from your SharePoint Management Console window

 #input parameters 
param($site, $queryText, $outputPath) 
 
 
# new keywordquery object 
$site = New-Object Microsoft.SharePoint.SPSite $site 
$query = New-Object Microsoft.office.Server.Search.Query.KeywordQuery $site 
 
# set ResultTypes 
$query.ResultTypes = [Microsoft.Office.Server.Search.Query.ResultType]::RelevantResults 
 
# set number of items to return 
$query.RowLimit = 10 
 
# actual string you are searching for 
$query.QueryText = $queryText 
 
# execute the query 
$resultTableColl = $query.Execute() 
 
# get the results back 
$resultTable = $resultTableColl.Item([Microsoft.Office.Server.Search.Query.ResultType]::RelevantResults) 
 
# make a DataTable from the results 
$resDataTable = $resultTable.Table 
 
# output the results, select the properties you want back, export to CSV file 
$resDataTable.Rows | Select-Object -Property Path,Title | Export-Csv -Path $outputPath