Friday, September 11, 2015

Changing the master page on SharePoint sites with PowerShell

On SharePoint Server 2010 publishing sites, you can change the name of the master page from the browser UI by going to Site Settings > Master page, under the “Look and Feel” section. However, as this option does not exist in the administration UI on team sites, each site in the site collection will retain a copy of its own master page by default, and it is not possible to change the name or location of it from the browser. For example, if you had one top level team site and five sub-sites, that is six separate master pages to manage for a relatively small structure.
One approach you may want to take is to store a central master page on the root site of the site collection and use PowerShell to change the master page setting for all sites in the site collection, pointing to the new name and location. To do this, first upload your new master page to the master page gallery on the root site of the site collection by going to Site Settings > Master pages under the “Galleries” section, clicking on the Documents tab, and uploading the new custom master page to the library:
image
if you want to change the master page setting for just one site, then use the script below:
$web = Get-SPWeb siteurl
$web.MasterUrl = "masterpagerelativeurl"
$web.Update()
$web.Dispose()
For the example site pictured above, the script would be as follows:
$web = Get-SPWeb http://portal/sites/collaboration
$web.MasterUrl = "/sites/collaboration/_catalogs/masterpage/custom.master"
$web.Update()
$web.Dispose()
Refreshing the root site in the browser will now show the new master page design, but all sub-sites will still show the old master page design – this is because they are each using a master page stored on their respective site. To change the master page setting for all sites in a site collection, use the following script:
$site = Get-SPSite http://portal/sites/collaboration
$site | Get-SPWeb -limit all | ForEach-Object { $_.MasterUrl = "/sites/collaboration/_catalogs/masterpage/custom.master";$_.Update() }
$site.Dispose()
Note that this will only change existing sites and will not set a custom master page for any new sites created. To update new sites, you will need to either run the script every time a new site is created, or use an alternative approach such as a feature receiver/stapler or Web provisioning event receiver to automatically set the new master page on site creation.
If you want to revert all team sites in the site collection back to using their own default master page again, then use the following script:
$site = Get-SPSite http://portal/sites/collaboration
$site | Get-SPWeb -limit all | ForEach-Object { $_.MasterUrl = $_.ServerRelativeUrl + "/_catalogs/masterpage/v4.master";$_.Update() }
$site.Dispose()

No comments:

Post a Comment