Sunday, April 1, 2012

Using PowerShell to set SharePoint 2010 MasterPage Recursively

During a recent development project to create a custom branded MasterPage for our 2010 portal, the page I had created had an EventReceiver that set the MasterPage to my custom MasterPage, however I forgot to enclose one of my vars with a semi colon and the page deployed but would not render, I kept getting a SharePoint error saying File not found!!! Even after retracting the solution with Visual Studio I kept getting the same error. I needed some way to reset the MasterPage to v4.master, enter PowerShell, my favorite way to work with admin task. Thanks to Todd Lindt's quick post found here:
http://www.toddklindt.com/blog/Lists/Posts/Post.aspx?ID=226

The master page setting is scoped at the web level, so the first thing I did was use Get-SPWeb to get a variable for the web I want to change. There are two properties that control the master page settings; MasterUrl and CustomMasterUrl. The former controls the master page used to render the System pages (the ones that start with /_layouts) and the latter controls the master page used to render the content pages.


To alter those settings for a publishing site at http://sharepoint/, use the following PowerShell script:

$web = Get-SPWeb http://sharepointurl/
$web.CustomMasterUrl = "/_catalogs/masterpage/customMasterPage.master"
$web.MasterUrl = "/_catalogs/masterpage/customMasterPage.master"
$web.Update()
This changes the master page for both settings and content to a customMasterPage.master. You can also set it to the default v4.master if you just need to reset it to the default masterpage. Since we're doing this with PowerShell it's easy to loop through a group of webs and set their master pages to whatever you like

No comments: