Thursday 19 January 2012

Add a Publishing Page and Set it to Default Welcome Page with custom Page Layout (PowerShell)

As part of a rather extensive process, i am currently writing a site structure deployment script that gets around the problem of being unable to deploy Publishing Sites from a template.

Instead, I've built my publishing site templates in a dev environment, exported the pages to XML, and using that xml, I am deploying brand new sites from the out of box Publishing template, and carefully reconstructing each site to match my template. I am doing this via powershell (of course) and using an excel sheet with all of the site types pre-defined.

A big issue I had was applying a custom page layout to the default.aspx page produced by the out of box template - I decided that this wasn't best practice and instead - I create a "Home.aspx" file, set it as default welcome page and apply my custom page layout.

As a taster, here's how I am creating the new pages, applying the custom page layout and setting them as default, welcome page BEFORE importing all of the default site content, and most importantly, the page content.

function CreatePages([string]$SiteUrl, [string]$PageLayoutName)
{

$site = New-Object Microsoft.SharePoint.SPSite($SiteUrl)
$psite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($site)
$web = Get-SPWeb $SiteUrl
$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)

#Create new Page(s)
$pl = $pubWeb.GetAvailablePageLayouts() Where { $_.Name -eq $PageLayoutName }
$newHomePage = $pubWeb.AddPublishingPage("home.aspx", $pl)
$newHomePage.Update()

# Check-in and publish page
$newHomePage.CheckIn("")
$newHomePage.ListItem.File.Publish("")

$newAboutPage = $pubWeb.AddPublishingPage("about-us.aspx", $pl)
$newAboutPage.Update()

# Check-in and publish page
$newAboutPage.CheckIn("")
$newAboutPage.ListItem.File.Publish("")


write-host "Published new page "

#Set new page to be the welcome (home page)
$assignment = Start-SPAssignment
$rootFolder = $web.RootFolder
$rootFolder.WelcomePage = "Pages/home.aspx"
$rootFolder.Update()
Stop-SPAssignment $assignment

write-host "Set as new default "

$site.Dispose()
$web.Dispose()

}

As you can see, I'm passing in just the "NAME" of the page layout, using [Microsoft.SharePoint.Publishing.PublishingWeb.GetAvailablePageLayouts() and a filter to bring back JUST that page layout.

Here we create the new page and apply the page layout.

$newHomePage = $pubWeb.AddPublishingPage("home.aspx", $pl)
$newHomePage.Update()


At some point, I will do a break down of the entire script. It does quite alot and is a pretty good alternative to a custom site defination. Although - given more time and resource, a custom site definition is the best way to solve this problem.


Have fun!
Ryan

1 comment:

  1. Nice post. Here is one more post explains the same..
    http://sureshpydi.blogspot.in/2014/03/change-default-homewelcome-page-in.html

    ReplyDelete