Created
February 6, 2018 01:36
-
-
Save andrewbbrown/140df144879eae895afcfa4cd59acf8e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| .Synopsis | |
| Converts a PowerShell object to a Markdown table. | |
| .EXAMPLE | |
| $data | ConvertTo-Markdown | |
| .EXAMPLE | |
| ConvertTo-Markdown($data) | |
| #> | |
| Function ConvertTo-Markdown { | |
| [CmdletBinding()] | |
| [OutputType([string])] | |
| Param ( | |
| [Parameter( | |
| Mandatory = $true, | |
| Position = 0, | |
| ValueFromPipeline = $true | |
| )] | |
| [PSObject[]]$collection | |
| ) | |
| Begin { | |
| $items = @() | |
| $columns = @{} | |
| } | |
| Process { | |
| ForEach($item in $collection) { | |
| $items += $item | |
| $item.PSObject.Properties | %{ | |
| if(-not $columns.ContainsKey($_.Name) -or $columns[$_.Name] -lt $_.Value.ToString().Length) { | |
| $columns[$_.Name] = $_.Value.ToString().Length | |
| } | |
| } | |
| } | |
| } | |
| End { | |
| ForEach($key in $($columns.Keys)) { | |
| $columns[$key] = [Math]::Max($columns[$key], $key.Length) | |
| } | |
| $header = @() | |
| ForEach($key in $columns.Keys) { | |
| $header += ('{0,-' + $columns[$key] + '}') -f $key | |
| } | |
| $header -join ' | ' | |
| $separator = @() | |
| ForEach($key in $columns.Keys) { | |
| $separator += '-' * $columns[$key] | |
| } | |
| $separator -join ' | ' | |
| ForEach($item in $items) { | |
| $values = @() | |
| ForEach($key in $columns.Keys) { | |
| $values += ('{0,-' + $columns[$key] + '}') -f $item.($key) | |
| } | |
| $values -join ' | ' | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment