functions/Read-EBMdBlockData.ps1

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
71
72
73
74
75
76
77
78
79
80
81
function Read-EBMdBlockData {
<#
    .SYNOPSIS
        Parses lines of a markdown block into a structured content set.
     
    .DESCRIPTION
        Parses lines of a markdown block into a structured content set.
        This assumes the lines of strings provided are shaped in a structured manner.
     
        Example Input:
     
        > Classes
     
        + Hunter Level 10
        + Warrior Level 12
     
        > Skills
     
        Bash
        Slash
        Shoot
     
         
        This would then become a hashtable with two keys: Classes & Skills.
        Each line within each section would become the values of these keys.
     
    .PARAMETER Lines
        The lines of string to parse.
     
    .PARAMETER Header
        What constitutes a section header.
        This expects each header line to start with this sequence, followed by a whitespace.
     
    .PARAMETER IncludeEmpty
        Whether empty lines are included or not.
     
    .EXAMPLE
        PS C:\> $components = $Data.Lines | Read-EBMdBlockData
     
        Read all lines of string available in $Data, returns them as a components hashtable.
#>

    [OutputType([hashtable])]
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [AllowEmptyCollection()]
        [string[]]
        $Lines,
        
        [string]
        $Header = '>',
        
        [switch]
        $IncludeEmpty
    )
    
    begin {
        $components = @{
            '_default' = @()
        }
        $currentComponent = '_default'
    }
    process {
        foreach ($line in $Lines) {
            if (-not $IncludeEmpty -and $line.Trim() -eq "") { continue }
            if ($line -notlike "$Header *") {
                $components.$currentComponent += $line
                continue
            }
            
            $componentName = $line -replace "^$Header "
            
            $currentComponent = $componentName
            $components[$currentComponent] = @()
        }
    }
    end {
        if (-not $components['_default']) { $components.Remove('_default') }
        $components
    }
}