Content Type Document Template – The right way.

Here is the code to set the document template for a Content Type such that when adding it the “Content Type” field in the library will be set properly.  Notice how you have to get the XmlSchema property for the _cts folder name (the content type name now, may not be the name later).

function SetDocumentTemplate($ctName, $filePath)
{
$fi = new-object system.io.fileinfo($filePath);

if (!$fi.exists)
{
return;
}

$contentTypes = $context.Site.RootWeb.ContentTypes
$context.Load($contentTypes)

try{
$context.executeQuery()
write-host "Getting Content Types - done." -ForegroundColor Green
}
catch{
write-host "Error While Fetching content types $($_.Exception.Message)" -foregroundcolor red
}

$contentType = $contentTypes | Where {$_.Name -eq $ctname}
$context.Load($contentType)
try{
$context.executeQuery()
write-host "Getting Content Type - done." -ForegroundColor Green
}
catch{
write-host "Error While Fetching $($ctName) content type $($_.Exception.Message)" -foregroundcolor red
}

[xml]$data = $contenttype.SchemaXml;

$folder = $context.Site.RootWeb.GetFolderByServerRelativeUrl("$($data.ContentType.Folder.Attributes["TargetName"].Value)");
#$folder = $context.Site.RootWeb.GetFolderByServerRelativeUrl("Document Templates")
#$ctsfolder = $context.Site.RootWeb.GetFolderByServerRelativeUrl("_cts");
#$subfolders = $ctsFolder.Folders;

$context.Load($folder)
#$context.Load($ctsfolder)
#$context.Load($subfolders)

try{
$context.executeQuery()
write-host "Loading folder done." -ForegroundColor Green
}
catch{
write-host "Error While Getting $($ctname) content type information $($_.Exception.Message)" -foregroundcolor red
}

<#
$enum = $subFolders.GetEnumerator();

while($enum.MoveNext())
{
write-host $enum.Current.ServerRelativeUrl;
}
#>

$templateName = $folder.ServerRelativeUrl + "/" + $fi.Name;

write-host "Uploading $($templateName) document template... " -NoNewline
$FileStream = New-Object IO.FileStream($filePath,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $fi.Name;
$Upload = $folder.Files.Add($FileCreationInfo)

$contentType = $contentTypes | Where {$_.Name -eq $ctname}
$context.Load($contentType)
try{
$context.executeQuery()
write-host " done." -ForegroundColor Green
}
catch{
write-host "Error While Uploading $($templateName) document template $($_.Exception.Message)" -foregroundcolor red
}

write-host "Setting $($ctname) content type document template... " -NoNewline
$contentType.DocumentTemplate = $fi.Name;
$contentType.Update($true)

try{
$context.executeQuery()
write-host " done." -ForegroundColor Green
}
catch{
write-host "Error While Setting $($ctname) content type document template $($_.Exception.Message)" -foregroundcolor red
}
}