Tip #692: Extract Word and Excel templates from CRM 2016 like a boss

The creativity of our fellow CRMers does not stop to surprise me. They go to the extraordinary lengths to avoid code because, as the true masters of their craft, they do not parade the skills just for the sake of it. But, as I was preparing the awesome tip #691 I couldn’t help but repeat “there must be a better way”.

Good developers write good code but

true developers only write code when there is no any other way or when the alternative is too painful to execute.

Military ExtractionTooth ExtractionExtracting the templates from CRM 2016 seem to be one of these cases. There are extractions and then there are extractions.
Compare setting up a fake workflow with the script that uses PowerShell module for Dynamics CRM Organization Data and extracts all templates including Excel ones into a temp folder in one sweet move:

Import-Module Microsoft.Xrm.Data.Powershell
$Global:conn = Get-CrmConnection -InteractiveMode

# get all template records
$templates = Get-CrmRecords `
    -EntityLogicalName documenttemplate `
    -Fields name,documenttype,content

# loop through the templates 
ForEach($t in $templates.CrmRecords) 
  # figure out file extension
  if($t.documenttype -eq 'Microsoft Excel') { 
    $ext = '.xlsx' 
  else {
    $ext = '.docx'
  $filename = 'c:\temp\' + $t.name + $ext
  write-host $filename

  # decode and dump file content 
  $bytes = [convert]::FromBase64String($t.content)
  [io.file]::WriteAllBytes($filename, $bytes)

Like a boss memePS. Credit where credit is due. After writing the script above I found the equivalent C# code, so I won’t be claiming land rights on this one.

Leave a Reply

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