Tuesday, April 26, 2011

"Save as Site Template" functionality for Publishing Sites via PowerShell

I came across a situation where I wanted to create a whole bunch of publishing sites, using one site as a template. Knowing that OOB, the "Save as Site Template" functionality is disabled (well kinda, you can always go straight to the url: /_layouts/savetmpl.aspx and give that a shot), I came up with an alternative using PowerShell.

What it's basically doing is exporting a site, creating a new site and then importing over the new site. The code is below:

# This creates sites based on the template provided.

function CreateWeb([string]$path, [string]$url, [string]$name)
{
Write-Host "Url: $url"
Write-Host "Path: $path"
Write-Host "Name: $name"

# Import the web that we saved
New-SPWeb -Url $url -Template "CMSPUBLISHING#0" -Name $name
Import-SPWeb -Identity $url -Path $path
$web = Get-SPWeb -Identity $url
$web.Title = $name
$web.Update()

# Change the Title of the page and publish it.
if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web))
{
$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$pages = $pubWeb.PagesList
foreach($item in $pages.Items)
{
$pubPage = [Microsoft.SharePoint.Publishing.PublishingPage]::GetPublishingPage($item)

$pubPage.CheckOut()
$pubPage.Title = $name
$pubPage.Update();
$pubPage.CheckIn("")
$pageFile = $pubPage.ListItem.File;
$pageFile.Publish("");
#$pageFile.Approve("");

}
}

$web.Dispose()

}

$path = "C:\Development\yourexportedweb.cmp"

# Create webs
CreateWeb $path "http://server/industries/financial" "Financial Services"
CreateWeb $path "http://server/industries/healthcare" "Healthcare"
CreateWeb $path "http://server/industries/insurance" "Insurance"

This is great for developers and admins, but not so much for end users, which is where the real need is. That'll have to be the next step...

No comments: