Sunday, December 6, 2009

How to change the site master page settings programmatically using PowerShell in SP2010

As I was involved in writing automation scripts to avoid the manual steps which we were intented to do, I wrote a powershell script to change the site master page settings programmatically...


$url = "http://servername"
$1 = "/_catalogs/masterpage/v4.master"
$2 = "/_catalogs/masterpage/nightandday.master"
$SPSite = Get-SPSite $url
$SPWeb = $SPSite.OpenWeb()
$SPSite.AllowUnsafeUpdates = "True"
## get the current status of the Site Master Page Settings in _Layouts/ChangeSiteMasterPage.aspx ##

$a = Get-SPSite $url
$b = $a.OpenWeb()
$c = $b.get_CustomMasterUrl()
$d = $b.get_MasterUrl()
$e = $b.get_AlternateCssUrl()
#### updating the SITE MASTER PAGE SETTINGS with the new ones ####

$Custmaster = $SPWeb.CustomMasterUrl ##Site Master Page - night
$SPWeb.CustomMasterUrl = $2
foreach($SubSite in $SPSite.AllWebs)

$SubSite.AllowUnsafeUpdates = "True"
$SubSite.CustomMasterUrl = $2
Write-Host "$SubSite updated"
$SPWeb = $SPSite.OpenWeb()

$SysMaster = $SPWeb.MasterUrl
## System Master Page - v4
$SPWeb.MasterUrl = $1
foreach($SubSites in $SPSite.AllWebs)
$SubSites.AllowUnsafeUpdates = "True"
$SubSites.MasterUrl = $1$SubSites.Update()
Write-Host "$SubSites updated"
$SPWeb = $SPSite.OpenWeb()

$SPWeb.AlternateCssUrl = "/Style Library/en-us/Core Styles/my_custom.css"
foreach($WebSubSites in $SPSite.AllWebs)
$WebSubSites.AllowUnsafeUpdates = "True"
$WebSubSites.MasterUrl = $1
Write-Host "$WebSubSites updated"



  1. Hi, I am new to PS. When I run the above script. It works correctly but the relative path to the masterpage is not found. I get an error in the log file stating that it can not find the master page at /_catalogs/masterpage/nightandday.master.
    Any ideas?

  2. The nightandday.master page is a publishing page.

    If it cannot find it have you tried enabling the publishing feature as a first port of call?