I have the following code to create a site and apply a custom template. It is working in my test environment that is created by backup-restore from my production portal.
This is the current script, based on the feedback in the comments:
#creates a site under the given url, based on the given template and title
Function CreateSite($parentUrl, $SubSiteUrl, $Template, $Title) {
try {
write-host "Read parent site"
$web = GET-SPWeb $parentUrl
write-host "reading template"
$wtemplate = $web.GetAvailableWebTemplates(1033) | Where-Object {$_.Title -eq $Template}
$url = $parentUrl + "/" + $SubSiteUrl
write-host "creating site"
$NewWeb = New-SPWeb -Url $url -Name $Title -UseParentTopNav
$web = GET-SPWeb $url
write-host "applying template"
#System.Object[]
$NewWeb.ApplyWebTemplate($wtemplate.Name)
write-host "done"
return "OK"
}
catch {
$ErrorMessage = $_.Exception.Message
if ($ErrorMessage -match 'is already in use.') {
try{
write-host "site exists, applying template"
$web = GET-SPWeb $url
$web.ApplyWebTemplate($wtemplate.Name)
return "OK"
}
catch{
$ErrorMessage = $_.Exception.Message
write-host $ErrorMessage
return ($ErrorMessage)
}
}
write-host $ErrorMessage
return ($ErrorMessage)
}
}
However, when I run it in my PRD server, I get the following error message on some of my sites:
Exception calling "ApplyWebTemplate" with "1" argument(s): "File or arguments not valid for site template 'System.Object[]'.
Update: Looks like we have double templates with the same title, but different names. However, these extra templates are not visible under "solutions" or in Designer, onder site templates like:
Name Title {A248FF57-5248-4C8B-9459-1B62703DACCD}#Customers Customers {CC69A307-7F92-47A7-8B6F-3981B480F9EA}#Customers Customers
So, the task is to remove one of these templates, but I did not find any code that removes a web template by name. The Uninstall-SPSolution accepts the wsp file name as parameter, but there is only one customer.wsp in the solutions library, so this will probably remove both. Deactivating, removing and uploading template to the solution library didn't help.