Integrating Open XML Functionality in a PowerShell Script by using Managed Code via the Add-Type Cmdlet

A question in a forum here at OpenXMLDeveloper.org clued me into a cool new way to add Open XML functionality into a PowerShell cmdlet –

PowerShell 2.0 and above enable you to directly embed C# code in a PowerShell script using the Add-Type cmdlet.  To use this cmdlet, you pass two arguments:

After calling the cmdlet, that type is available for your use in your PowerShell script.  I’ve recorded a short video showing this approach.  Here is the script that I show in the video (which is at the bottom of this post).

$assem = (
 
"windowsbase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35",
 
"DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
)

$source
= @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

public class BasicTest
{
  public static string DoOpenXmlFunc(string fileName)
  {
    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(fileName, false))
    {
      var paragraphs = wDoc.MainDocumentPart.Document.Descendants<Paragraph>();
      return paragraphs.Count().ToString();
    }
  }
}
"
@

Add-Type -ReferencedAssemblies $assem -TypeDefinition $source
[BasicTest]::DoOpenXmlFunc(".\test.docx")

Happy scripting!