Tuesday, May 22, 2012

Create a SharePoint sub site from a site export

Our issue was some 3rd party web parts were not allowing us to save a site as a template through the normal way of going into the Site Actions > Site Settings > Save Site as a template.

Our solution involved using Powershell to do an export of the site we wanted to use as a template. The main challenge with this is that you need to first create a SharePoint site, then do an Import-SPWeb to restore the site that was exported, then set the title and description. (This works with both http and https sites.)

# Define root site where the shell of the sub site will be created under
$site = "https://portal/"
   
Write-Host "Please enter the Title of the site to create"       
$webTitle = Read-Host "Please enter the title of the site you wish to create"    
$newSiteUrl = "https://portal/$webTitle"     
# Create empty subsite
$web = New-SPWeb $newSiteUrl -name $webTitle -UseParentTopNav
# Use the base SharePoint template of STS#1
$web.ApplyWebTemplate("STS#1")
# Give the site a name
$web.Name = $webTitle
# Apply changes
$web.Update()
# Since we are using a custom template for the sites we will want to set some variables
$templateName = "https://portal/$webTitle"
$templateLocation = "C:\Temp\Template\site.bak"
# Restore the site from the back up
Import-SPWeb $templateName -Path $templateLocation -IncludeUserSecurity
# We need to update some properties of the restored site, so we set the site as a variable
$web = (Get-SPWeb -Identity "https://portal/$webTitle")
# Once the site is restored this will overwrite the title and description which we set here
$web.title =$webTitle
$web.description = "Template Site"
# Update the site
$web.update()
# Clean it up
$web.dispose()
  
Write-Host "The Installation is complete please visit the site at" $web.URL

No comments: