Friday, July 11, 2014

Create Sharepoint sites with web templates from sandbox solution using PowerShell

In order to create sub sites in Sharepoint site collection we may use New-SPWeb cmdlet. It has Template parameter in which we may specify what template should be used for the new site. This parameter has SPWebTemplatePipeBind type, i.e. instead of passing string to it we need to get instance of appropriate web template first. If you remember OTB web template names differ from custom web templates provisioned via features: for OTB they look like “template name#id”, e.g. “STS#0” (also it looks like this for custom site templates provisioned in old style via copying onet.xml directly to SiteTemplates sub folder in Sharepoint hive, not via features), while for custom web templates name look like “feature id#template name”, e.g. “{e7fc7957-cfdc-47d7-8afa-3cb8dc3f199e}#Test”.

One of the way to get web template instance in PowerShell it is to use another cmdlet Get-SPWebTemplate. Unfortunately it doesn’t work for custom web templates provisioned with sandbox solution. In this case it will always show “The web template does not exist” error.

Another try may be to get instance from list of all web templates try to create site with it:

   1: $template = $site.GetWebTemplates($lang) | Where-Object {$_.Name -eq $templateName}
   2: $web = New-SPWeb -Url $url -name $title -Template $template -Language $lang

However although web template instance will be correctly retrieved in this example, call to New-SPWeb will show the following warning:

WARNING: Template is not found and is not applied.

Site will be created, but when you will try to navigate to the created web, OTB template picker will be shown and will ask you to choose web template.

In order to avoid this problem we need to create sub site without template, and then call SPWeb.ApplyWebTemplate() method on the created instance:

   1: $template = $site.GetWebTemplates($lang) | Where-Object {$_.Name -eq $templateName}
   2: $web = New-SPWeb -Url $url -name $title -Language $lang
   3: $web.ApplyWebTemplate($template.Name)

After that sub site should be created successfully from custom web template which is provisioned with sandbox solution. Instead of SPSite.GetWebTemplates() method which returns list of all available web templates you may use SPWeb.GetAvailableWebTemplates() which returns list of allowed web templates for specific site. However sometimes from PowerShell you need to create sites using those web templates which are not allowed for regular users for creating sites from UI. In this case SPSite.GetWebTemplates() method should be used.

No comments:

Post a Comment