Add Document Template to Content Type in SharePoint using PowerShell

Requirement:  Associate document template with content type in SharePoint.

PowerShell to add document template to a content type in SharePoint

Here is the PowerShell to upload a document template to a content type in SharePoint:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
#Parameters
$SiteURL="https://intranet.crescent.com"
$ContentTypeName="Crescent Invoice Template V2"
$DocumentTemplatePath="C:\Temp\Crescent Invoice Template V3.docx"

Try {
    #Get the Web and Content Type
    $Web = Get-SPWeb $SiteURL
    $ContentType = $Web.ContentTypes | Where {$_.Name -eq $ContentTypeName}
 
    #Check Cotent type and document template exists
    If($ContentType -ne $null -and [System.IO.File]::Exists($DocumentTemplatePath))
    {
        #Get the Template File
        $TemplateFile =(Get-ChildItem $DocumentTemplatePath).OpenRead()

        #Get the Template File Name
        $DocumentTemplateFileName = [System.IO.Path]::GetFileName($DocumentTemplatePath)

        #Upload the document Template  
        $DocumentTemplate = $ContentType.ResourceFolder.Files.Add($DocumentTemplateFileName, $TemplateFile,$True)

        #Set Document Template of the Content type
        $contentType.DocumentTemplate = $DocumentTemplateFileName
        $contentType.UpdateIncludingSealedAndReadOnly($True)
  
        Write-Host -f Green "Added Document Template $DocumentTemplateFileName to $ContentTypeName"
    }
    Else
    {
        Write-host -f Yellow "Cannot find Content Type $ContentTypeName or document template file $DocumentTemplatePath!"
    }
}
Catch {
    write-host -f Red "Error Adding Document Template to Content Type!" $_.Exception.Message
}

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

Your email address will not be published. Required fields are marked *