FormatMarkdown.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
function Format-Markdown {
    <#
    .Author
    Trevor Sullivan <trevor@trevorsullivan.net>
    http://trevorsullivan.net
 
    .Synopsis
    Formats an array of objects as a Markdown table.
 
    .Parameter Properties
    The -Properties parameter accepts an array of System.String objects, which
    represents the properties that will be retrieved from the input objects.
 
    .Parameter InputObject
    The -InputObject accepts an array of arbitrary objects. The objects should
    all be of the same type. If the input objects are of different types, then
    the output from this command will be unpredictable.
 
    .Example
    Get-Process -Name *b* | Format-Markdown -Properties Id,Name,WorkingSet;
 
    .Example
    Format-Markdown -Properties Name,Status,DisplayName -InputObject (Get-Service);
    #>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true, Mandatory = $true)]
        [System.Object[]] $InputObject
      , [string[]] $Properties = '*'
    )

    begin {
    }

    process {
        $Params = $PSBoundParameters;
        foreach ($Item in $InputObject) {
        $MDString += "`n";
        foreach ($Property in ($Item | Get-Member -MemberType Property,NoteProperty,AliasProperty,ScriptProperty -Name $Properties)) {
            $MDString += '|{0}' -f ($Item.$($Property.Name));
        }
        $MDString += '|';
        }
    }

    end {
        $Header = '';
        foreach ($Property in ($InputObject | Get-Member -MemberType Property,NoteProperty,AliasProperty,ScriptProperty -Name $Properties)) {
            $Header += '|{0}' -f $Property.Name;
        }
        $Header += '|';
        $MDString = $MDString.Insert(0, $Header);
        Write-Output $MDString;
    }
}

### Create an alias for the Format-Markdown command
New-Alias -Name fmd -Value Format-Markdown -Description 'Formats an array of similar objects as a Markdown table.';

### Export the command and alias explicitly
Export-ModuleMember -Function Format-Markdown -Alias fmd;