0

I'm trying to make a PowerShell script using the DocumentFormat.OpenXml library. Everything is working fairly well, except that I'm struggling with syntax for passing type parameters. Specifically, I'm working with the DocumentFormat.OpenXml.OpenXmlElement.Descendants method. I can easily call it like this:

using assembly /root/.nuget/packages/documentformat.openxml/2.17.1/lib/net40/DocumentFormat.OpenXml.dll;
using namespace DocumentFormat.OpenXml;

$Output = Resolve-Path "$(Get-Location)\out.docx"
$myDoc = [WordprocessingDocument]::Open($Output, $true)
$mainPart.Document.Body.Descendants()

This returns all of the descendants. However, I'd really like to call $mainPart.Document.Body.Descendants<FormFieldData>() to get only descendants of that type. Unfortunately, PowerShell doesn't like the <> syntax. It gives me this message:

At line:1 char:36
+ $mainPart.Document.Body.Descendants<FormFieldData>()
+                                    ~
The '<' operator is reserved for future use.

I'm sure this is simply a matter of not knowing the correct PowerShell syntax, but my Google skills are failing me and I can't seem to find the correct syntax.

Kevin Rak
  • 336
  • 2
  • 14
  • 1
    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_calling_generic_methods?view=powershell-7.3 Try `$mainPart.Document.Body.Descendants[FormFieldData]()` – Charlieface Jul 28 '22 at 16:09
  • @Charlieface nice! Unfortunately I'm on version 5 for the moment so that syntax doesn't work. Perhaps I can fix the version, since the link you sent seems to indicate that prior to version 7 things were a lot harder. – Kevin Rak Jul 28 '22 at 16:15
  • @Charlieface that got me there! Thank you! If you make this an answer, then I will mark it as the solution. Once I copied the script from that answer, I was able to do: `.\Invoke-GenericMethod.ps1 -instance $mainPart.Document.Body -methodName Descendants -typeParameters DocumentFormat.OpenXml.Wordprocessing.FormFieldData -methodParameters $null` – Kevin Rak Jul 28 '22 at 16:30
  • You should have a button above to accept the link as a duplicate – Charlieface Jul 28 '22 at 19:42

0 Answers0