Monday 8 July 2013

Swap Page Layout

Six months ago you created a page layout with a custom content type, everything went great but the time has come to add some more meta-data (another field/column) to your content type. First of all you may or may not know this but you can’t just overwrite your page layout, well you could but that will not update your existing pages with the new layout. What you must do instead, create a new page layout, than update all of your existing pages to use the new layout.

You may have run the standard script, changed your page layout, but the content type is out of whack. That or maybe you started swapping the layout using the UI and thought wow there’s got to be a better way; and that way is through PowerShell, here’s the script that I use, but remember your new content type has to be added to the Pages document library content types, in the list settings.

function LoadSharePointPowerShellEnviroment
 write-host "Setting up Powershell enviroment for Sharepoint" -foregroundcolor Blue
 Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
 Write-host "Sharepoint PowerShell Snapin loaded." -foregroundcolor Green

$web = Get-SPWeb("http://yoursite/yourweb")

$newCT = $web.lists["Pages"].ContentTypes["New Page Layout"]
$newPageLayout = "/_catalogs/masterpage/NewLayout.aspx, New Page Layout"
$oldContentTypeName = "Old Page Layout"

foreach($page in $web.lists["Pages"].Items)
    $file = $web.GetFile($page.url)
    if($page.ContentType.Name -eq $oldContentTypeName)
        Write-host  $page.url -foregroundcolor blue
        $file.CheckOut("Online", $null)
        $file.Properties["PublishingPageLayout"] = $newPageLayout
        $file.Properties["ContentTypeId"] = $newCT.Id.ToString()
        $file.CheckIn("Update page layout via PowerShell",[Microsoft.SharePoint.SPCheckinType]::MajorCheckIn)
        $file.Approve("Approved through PowerShell")

one thing that you can note that's different from the standard swap page layout script that you'll see floating around on the internet is that I also update the content type Id on the file properties, if you don't do this they page layout will change, but the content type will still be in use if you try to remove it form the page layout. 
Three things of note:
  • Make sure all of your pages with the old layout are checked in before you run this script, or update the script to check them in for you.
  • If you still can't remove the page layout from the library after running this script, odds are it's a problem in your content database; at least that's where my research led me, and as you may know any direct modifications to your content database will result in it not being supported by Microsoft. Thus I abandoned that avenue and just hid it on the new button in the list settings.
  • Your file properties are case sensitive PublishingPageLayout is fine, but publishingPageLayout will not work.