How to set all webs (sub sites as some call them) in a site collection, to use a common master page

In environments where the publishing features aren’t used (or desired), or available (such as SharePoint Foundation installs, being able to set all webs (Sub sites) in a site collection to a common Master Page using PowerShell is very useful. Here’s how…

$site = Get-SPSite http://portal.somewhere.com/ 
$sites = @(foreach ($web in $site.AllWebs) { 
$web | Select-Object -Property Url 
Write-Debug "Setting master pages in web ($($web.Url))..." 
$web.MasterUrl = "/_catalogs/masterpage/your_custom_page.master" 
$web.Update() 
$web.Dispose() 
}) | out-File -filepath "c:masterpagesmodifiedOutput.txt" 
$site.Dispose() 

 

The above will go through all the webs in the chosen site collection URL (in this case, http://portal.somewhere.com, but could easily be http://portal.somewhere.com/sites/HR) and set the master page to the desired master page and will produce a text file outlining which webs it found along the way. Items in bold black will need to be set to suit.

To Run It

  1. Save the above after you have customized it as pushmasterpages.ps1 (using notepad, or whatever…)
  2. Open SharePoint 2010 Management Shell (Powershell)
  3. Launch Powershell against that file (assuming it is in the root of C:), that would be:
.pushmasterpages.ps1
 
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }