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.

Update: 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[]'.

I checked, and the templates are the same in both places. I don't have powershell access on the PRD machine, so I cannot do any debugging, but the only thing that I can think of is that there are multiple templates with the same title, that are not visible neither in the GUI nor in Designer. I am not sure if this is even possible, but can someone help me how to return the last, active template with this line:

    $wtemplate = $web.GetAvailableWebTemplates(1033) | Where-Object {$_.Title -eq $Template}

Ideas for other root cause are also very welcome.

Update 2: Looks like we indeed have double templates with the same name, but different ID. However, these extra templates are not visible under "solutions" or in Designer, onder site templates.