Change Master Page in SharePoint using PowerShell
Requirement: Change Master page for SharePoint Site collections.
After a branding redesign project, Got a requirement to change master pages on existing sites. branding on new sites going to be created. But for existing sites, We got to change master pages manually.
SharePoint: Set master page using PowerShell
Let’s change master page in SharePoint using PowerShell.
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue
#Get the Web
$web = Get-SPWeb "https://intranet.crescent.com/branding"
#Prepare the Custom Master page URL
$WebURL = $web.ServerRelativeUrl.TrimEnd("/")
$MasterPageURL = $WebURL+"/_catalogs/masterpage/crescentv1.master"
#Set Default and Custom Master pages
$web.MasterUrl = $MasterPageURL
$web.CustomMasterUrl = $MasterPageURL
#Apply Changes
$web.Update()
Change master page SharePoint 2013 using PowerShell
How about All sites in a site collection? Here is the PowerShell script in SharePoint 2013 to change the master page.
#Variable for Site collection
$SiteURL ="https://intranet.crescent.com"
#Get the Site object
$site = Get-SPSite $SiteURL
#Iterate through each web
foreach ($web in $site.AllWebs)
{
#Prepare the Custom Master page URL
$WebURL = $web.ServerRelativeUrl.TrimEnd("/")
$MasterPageURL = $WebURL+"/_catalogs/masterpage/crescentv1.master"
$web.MasterUrl = $MasterPageURL;
$web.CustomMasterUrl = $MasterPageURL;
$web.Update();
Write-Host "Master page set for: $web.Url
}
We can modify the above code to apply master page for entire web application, even entire SharePoint farm!
The script is incorrect beside a syntax error on line 19
The $MasterPageURL is built up by de web url this must be the site collection url
otherwise the url is wrong with a site collection having one or more subsites (webs)
and then the $MasterPageURL can be set before the loop as it wont change anymore for all the sub sites (webs)
If you run the above script subsite wont open and will give a file not found (because of the incorrect master url).
Well, that depends on how you have deployed the master page! Ideally, it should be deployed at each web – while its possible to inherit from the site collection.