Apply Custom Master Page to all Site Collections

I’ve just upgraded my MOSS 2007 site to SharePoint 2010. Oh No! The Master Page for 2007 doesn’t work in 2010 and I have 1500 Site Collections each with three websites!!

I need to activate my Master Page feature on each site collection and apply it to every site. Back in the old days, I would enumerate sites and create a huge script in excel to activate features and apply the Master Page. This is quite time consuming especially if you are upgrading different web applications every day. I thought it was time I tried to make this job easier and faster using PowerShell.

First start by looping though all the site collections in the web application then loop through the all the websites in the site collection (nested loop to get to every web in the web application). Then retrieve the URL of the web application and the URL of the site collection.
If the site is using a managed path for the site collections, it needs to be the relative path to the Master Page from the root of the web application.

e.g.

Web Application: http://www.tonyishere.co.uk
Site Collection: http://www.tonyishere.co.uk/sites/accounts
So the Master Page URL would be:  /sites/accounts/_catalogs/masterpages/custom.master

So how do we find the MasterPage URL path (as seen above) for each site collection? Using the length of the URL strings, the web application URL can be broken into a substring and appended to create the right path (see below).

e.g.
$len2 = $webname.length - 1
$len = $webappname.length
$len3 = $len2 - $len
$masterpath = $webUrl.substring($len,$len3)
$masterpath = $masterpath += "/_catalogs/masterpage/custom.master"

The new Master Page path then needs to be applied to the website.

$web.CustomMasterUrl = $masterpath

I found looping through 4500 websites in 1500 site collections took about 9 seconds, compared with the four hours that stsadm would of taken….big difference!!

Here is my full script to activate the feature on the site collection and loop into each website and apply the Master Page.


$webapp = Get-SPWebApplication https://www.tonyishere.co.uk
foreach ($s in $webapp.sites)
{
Enable-SPFeature MyCustomMasterPageFeature -Url $s.url
foreach ($web in $s.AllWebs)
{
$webUrl = $web.url
$web = Get-SPWeb $webUrl
$webappname = $webapp.url
$len2 = $webname.length - 1
$len = $webappname.length
$len3 = $len2 - $len
$masterpath = $webUrl.substring($len,$len3)
$masterpath = $masterpath += "/_catalogs/masterpage/custom.master"
$web.CustomMasterUrl = $masterpath
$web.MasterUrl = $masterpath
$web.Update()
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *