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()
$c
$d = $b.get_MasterUrl()
$d
$e = $b.get_AlternateCssUrl()
$e
#### updating the SITE MASTER PAGE SETTINGS with the new ones ####

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

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

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

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

--------------------

2 comments:

  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?
    Thanks
    Frank
    ffcardil@gapac.com

    ReplyDelete
  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?

    ReplyDelete