PSMarkdig.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
function Get-MdDocument
{
  [cmdletBinding(DefaultParameterSetName='byString')]
  [OutputType([Markdig.Syntax.MarkdownDocument])]
  param
  (
    [Parameter(Mandatory,ParameterSetName='byString')]
    [string]$String,

    [Parameter(Mandatory,ParameterSetName='byFile')]
    [System.IO.FileInfo]$FilePath,

    [Parameter()]
    [string[]]$Extension
  )

  process
  {
    #Get markdown string
    switch ($PSCmdlet.ParameterSetName)
    {
      'byString' {
        $mdString = $String
        break
      }

      'byFile' {
        $mdString = Get-Content -Path $FilePath -Raw
        break
      }
    }

    #Parse markdown
    $pipeline = [Markdig.MarkdownPipelineBuilder]::new()
    if ($PSBoundParameters.ContainsKey('Extension'))
    {
      $pipeline = [Markdig.MarkDownExtensions]::Configure($pipeline,($Extension -join '+'))
    }
    $result = [Markdig.Parsers.MarkdownParser]::Parse($mdString,$pipeline.Build())
    $PSCmdlet.WriteObject($result,$false)
  }
}

function Get-MdElement
{
  [cmdletBinding()]
  param
  (
    [Parameter(Mandatory)]
    [Markdig.Syntax.MarkdownDocument]$Document,

    [Parameter(Mandatory)]
    [string]$TypeName
  )

  process
  {
    #Check Type
    $type = $TypeName -as [Type]
    if (-not $type)
    {
      throw "Type: '$TypeName' not found"
    }

    $mdExtensionsType = [Markdig.Syntax.MarkdownObjectExtensions]
    $methodDescendants = [Markdig.Syntax.MarkdownObjectExtensions].GetMethod('Descendants',1,[Markdig.Syntax.MarkdownObject])
    $method = $methodDescendants.MakeGenericMethod($Type)
    $method.Invoke($mdExtensionsType,@(,$Document)) | ForEach-Object {$PSCmdlet.WriteObject($_,$false)}
  }
}