Wednesday, September 26, 2012

Upload content type template through PowerShell

In my current project, we make use of numerous different Word templates. To make template a part of the automated build process, I made a PowerShell script that

  1. Loop through a folder on the disk
  2. Find subfolder, named in a given way
  3. Find the template
  4. Finds the content type in SharePoint
  5. Upload the template to the content type resource folder http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontenttype.resourcefolder.aspx
  6. Save the content type

And the content type is ready to get published.

PowerShell script:

1 Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction:SilentlyContinue | Out-Null
2 $url = "http://win-l2sfc3oetnn/sites/doctemp/" #ContentTypeHub Url
3 $templateFolderPath = "C:\Projects\demos\TemplateDemo"
4 $filter = "*.dotx", "*.potx", "*.vst", "*.xltx"
5
6 $contentTypeFolders = ls $templateFolderPath | where {$_.PsIsContainer}
7 $templateCount = (ls $templateFolderPath -Include $filter -Recurse | where {!$_.PsIsContainer}).Count
8 $i = 1
9 $fileMode = [System.IO.FileMode]::Open
10
11 $contentTypeFolders | % {
12 $path = $_.FullName
13 $foldername = $_.Name
14 $ctindex = $foldername.LastIndexOf("0x")
15
16 if($ctindex -gt 0) {
17
18 $contenttypeid = $foldername.Substring($ctindex, $foldername.Length - $ctindex)
19 $spcontenttypeid = New-Object Microsoft.SharePoint.SPContentTypeId $contenttypeid
20
21 ls -Path $path | % {
22 #Need to open a new spweb object, to "refresh" the current content type object, to aviod database update conflict
23 $web = Get-SPWeb $url
24 $spcontenttype = $web.ContentTypes[$spcontenttypeid]
25 $fileFullname = $_.FullName
26 $filename = $_.Name
27
28 Write-Progress -PercentComplete (($i / $templateCount) * 100) -Activity "Uploading templates" -Status "$filename on content type $($spcontenttype.Name)"
29
30 $i++
31 try{
32 #open the document template, as a filestream
33 $fileStream = New-Object "System.IO.FileStream" -ArgumentList $fileFullname, $fileMode
34 #add the file (SPFile) to the content type resource folder http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontenttype.resourcefolder.aspx
35 $spcontenttype.ResourceFolder.Files.Add($filename, $fileStream, $true) | Out-Null
36 $fileStream.Close()
37 #set the current document template file to be the document tmeplate
38 $spcontenttype.DocumentTemplate = $filename
39 #update the content type
40 $spcontenttype.Update($true)
41 }
42 finally{
43 $fileStream.Close()
44 }
45 }
46 }
47 }

Download link

No comments:

Post a Comment