Use PowerShell to modify SharePoint 2010 search results web part properties

As you know, your SharePoint 2010 Search results page is just another publishing page which you can: check out, modify web parts on, and check back in.
In this post, I wanted to share an approach for modifying the Core Search Results web part properties on your search page.
PowerShell approach outlined here will allow you to make appropriate modifications and transfer those between your environments as you need to make changes.
I am assuming you’re running a demo environment which has SharePoint 2010 with Enterprise search installed. I also assume your root site www.contoso.com has a search sub-site under it with the URL: http://www.contoso.com/search.
Open SharePoint 2010 Management Shell and execute the following script:

# Defining script variables
$SiteUrl = "http://www.contoso.com"

# Loading Microsoft.SharePoint.PowerShell
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null) {
Write-Host "Loading SharePoint Powershell Snapin"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

$SPSite = Get-SPSite | Where-Object {$_.Url -eq $SiteUrl}
  if($SPSite -ne $null)
  {
  Write-Host "Connecting to search site"
  $SearchWeb = $SPSite.OpenWeb("/search")
  $pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($SearchWeb)

  Write-Host "Retrieving the search results page"
  $resultsPage=$pubWeb.GetPublishingPages() | Where-Object {$_.Name -eq "results.aspx"}
  $resultsPage.CheckOut()
  $webPartManager=$SearchWeb.GetLimitedWebPartManager($resultsPage.Url,
[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

  Write-Host "Modifying properties of search box web part"
  $searchResults = $webPartManager.WebParts | Where-Object {$_.Title -eq "Search Core Results"}
  $searchResults.ResultsPerPage = 25
  $webPartManager.SaveChanges($searchResults)

  Write-Host "Checking in and publishing changes"
  $resultsPage.CheckIn("Checked in Webpart")
  $resultsPage.listItem.File.Publish("Published Webpart")

  $SearchWeb.Dispose()
  }
$SPSite.Dispose()

The key idea here is that we connect to the web part manager object on the page in order to make modifications to our page.
When done with the changes, we call the SaveChanges method on the web part manager to save the web part.
You can change any web part on any other SharePoint search page, just by specifying the appropriate page name:

$resultsPage=$pubWeb.GetPublishingPages() | Where-Object {$_.Name -eq "results.aspx"}

To get a hold of the web part when you already have the page context, just search for the web part title or another unique attribute as below:

$searchResults = $webPartManager.WebParts | Where-Object {$_.Title -eq "Search Core Results"}

Enjoy!

This entry was posted in sharepoint 2010 and tagged , , , . Bookmark the permalink.

Comments are closed.