Created
January 27, 2024 00:25
-
-
Save JustinGrote/595973381d6438d987552d6a33851515 to your computer and use it in GitHub Desktop.
Convert PowerShell Objects to Markdown Display by screen-scraping Format-Table
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
using namespace System.Collections.Generic | |
using namespace Microsoft.PowerShell.Commands.Internal.Format | |
#Inspired by: https://gist.github.com/aaroncalderon/09a2833831c0f3a3bb57fe2224963942 | |
<# | |
.Synopsis | |
Converts PowerShell Objects or Format-Table output to Markdown | |
#> | |
Function ConvertTo-Markdown { | |
[CmdletBinding()] | |
[OutputType([string])] | |
Param ( | |
[Parameter(Mandatory, ValueFromPipeline)][PSObject[]]$inputObject | |
) | |
begin { | |
$inputObjects = [List[object]]::new() | |
} | |
process { | |
$inputObjects.Add($inputObject) | |
} | |
end { | |
if ($inputObjects[0].GetType().Name -ne 'FormatStartData') { | |
$inputObjects = $inputObjects | Format-Table -AutoSize -GroupBy "$(New-Guid)" # This effectively filters any grouping | |
} | |
if ($inputObjects.GetType().Name -contains 'GroupStartData') { | |
throw [NotSupportedException]'Grouped Tables are not supported' | |
} | |
[string[]]$stringify = ($inputObjects | Out-String).split([Environment]::NewLine) | Where-Object length | |
#We use the dash line because the line above might have spaces in property names | |
$headerDashLine = $stringify[1] | |
[int[]]$headerIndexes = ($headerDashLine | Select-String -Pattern '-+' -AllMatches).Matches.Index | |
$line = 0 | |
foreach ($currentLine in $stringify) { | |
# Insert | into the string at the header indexes | |
$i = 0 | |
foreach ($index in $headerIndexes) { | |
$currentLine = $currentLine.Insert(($index + $i), '|') | |
$i++ | |
} | |
$line++ | |
"$currentLine|" + [Environment]::NewLine | |
continue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment