Tuesday, November 2, 2010

PowerShell: Swapping Master Pages of Second Level Site Collections

I kept running into a File Not Found error when using my PowerShell MasterPage swapping scripts in our environment with 50+ site collections.  Turns out a slight modification is needed when working with site collections that live on the second level (ie not the root).  You need to add the Server Relative Url (/sitecoll) to the masterpage path (/_catalogs/masterpage), and you can accomplish that with this:

# First run this to activate the features
$webApp = Get-SPWebApplication -Identity http://webappurl;
$webApp | Get-SPSite -limit all | ForEach-Object {
  $siteurl = $_.Url;
  if ($siteurl -ne "http://webappurl")
  {
  Write-Host $siteurl;
  $result = Enable-SPFeature -Identity "[SiteCollecitonFeatureName]" -Force -Url $siteurl;
  Write-Host $result;
  }
}

# then run this to swap the masterpages
$webapps = Get-SPWebApplication http://webappurl;
foreach ($site in $webapps.Sites){
    Write-Host $site.url;
    $web = $site.openweb();
    $siteurl = $site.ServerRelativeUrl.TrimEnd('/');
    Write-Host "siteurl:  $siteurl";

    $web.MasterUrl = $siteurl + "/_catalogs/masterpage/[FEATURE FOLDER]/ShinyNew.master";
    $web.CustomMasterUrl = $siteurl + "/_catalogs/masterpage/[FEATURE FOLDER]/ShinyNew.master";
    $web.Update();

    $web.Dispose();
    $site.Dispose();
}

No comments: