Skip to content

Instantly share code, notes, and snippets.

@JustinGrote
Created January 27, 2024 00:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinGrote/595973381d6438d987552d6a33851515 to your computer and use it in GitHub Desktop.
Save JustinGrote/595973381d6438d987552d6a33851515 to your computer and use it in GitHub Desktop.
Convert PowerShell Objects to Markdown Display by screen-scraping Format-Table
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