Select-PSFormatTable.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
#Inspired by: https://seeminglyscience.github.io/powershell/2017/04/20/formatting-objects-without-xml
using namespace System.Management.Automation
using namespace System.Collections.Generic
function Select-PSFormatTable {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory,ValueFromPipeline)]$InputObject,
        [String[]]$Property,
        [String]$Name = 'Custom',
        [String]$TypeName,
        [String]$Path
    )
    begin {
        $ExtendedTypeDefinitions = [List[ExtendedTypeDefinition]]::new()
    }
    process { 
        foreach ($InputObjectItem in $InputObject) {
            if (-not $TypeName) {$TypeName = $InputObject.GetType().FullName}
            if (-not $Property) {$Property = $InputObject.psobject.properties.name}
            $tableControl = [TableControl]::Create($true, $true, $false)
            $rowDefinition = $tablecontrol.startrowdefinition($false)
            $InputObjectProperties = $InputObject.psobject.properties.name
            $Property.foreach{
                if ($PSItem -notin $InputObjectProperties) {throw "Property $PSItem doesn't exist on the provided object."}
                [void]$TableControl.AddHeader('Undefined',0,$PSItem)
                [void]$rowDefinition.AddPropertyColumn($PSItem)
            }
            [void]$rowDefinition.EndRowDefinition()
            $tableControl = $tableControl.EndTable()
            $ExtendedTypeDefinitions.Add(
                [ExtendedTypeDefinition]::new(
                    $TypeName,
                    [FormatViewDefinition]::new($Name, $TableControl) -as [List[FormatViewDefinition]]
                )
            )
        }
    }
    end {
        if ($Path) {
            $ExtendedTypeDefinitions | Export-FormatData -Path $Path
        } else {
            return $ExtendedTypeDefinitions
        }
    }
}