Wednesday, November 19, 2014

PowerShell Updating the Page Layout of a Publishing Page

Here is the simple and efficient PS script to update the page layout of a page, if you have both page and layout urls.

While changing the page layout of a publishing page in SharePoint, make sure that the page is of the same content type that is associated with the page layout.
#Add sharepoint snapin
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

#Get publishing web, site and page
$spWeb = Get-SPWeb("http://sampleweb.com")
$pWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb)
$pSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($spWeb.Site);
$pubPage = $pWeb.GetPublishingPage("http://sampleweb.com/Pages/testpage.aspx") 

#Get page layout
$siteLayouts = $pSite.GetPageLayouts($false)
$myLayout = $siteLayouts["/_catalogs/masterpage/mylayout.aspx"] 

#Update page layout of a page
$pubPage.CheckOut() 
$pubPage.Layout = $myLayout 
$pubPage.ListItem.Update() 
$pubPage.CheckIn("Updated page layout via PowerShell")

$spWeb.Dispose()