Skip to content

Instantly share code, notes, and snippets.

@BenNeise
Last active January 12, 2021 18:26
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save BenNeise/4c837213d0f313715a93 to your computer and use it in GitHub Desktop.
Save BenNeise/4c837213d0f313715a93 to your computer and use it in GitHub Desktop.
ConvertTo-Markdown
<#
.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 ' | '
}
}
}
@mac2000
Copy link

mac2000 commented Apr 17, 2015

Thank you for the idea

Forked your script and some sugar to output so now it looks more like a ascii table:

Region        | Category   | Count
------------- | ---------- | -----
UK            | java       | 35   
UK            | javascript | 34   
CA            | javascript | 27   
CA            | java       | 27   
NY            | java       | 23   
allows remote | javascript | 22   
Deutschland   | java       | 21   
UK            | c#         | 21   
CA            | python     | 21   
UK            | php        | 20

@BenNeise
Copy link
Author

Thanks, I've merged your changes!

@sabujp
Copy link

sabujp commented Sep 29, 2015

useful script, I made some changes here to get rid of the null value issue : https://gist.github.com/sabujp/1a3b2e0c2d6662e3ffc5#file-convertto-markdown-ps1 . Hopefully you can merge the changes if it looks ok.

@aaroncalderon
Copy link

Hi,

I also stumbled upon this grate script, however, i was having issues when I piped the output to a function that appends to a file.

I just added the ``n` new line to each line that outputs text, and it worked.

https://gist.github.com/aaroncalderon/09a2833831c0f3a3bb57fe2224963942

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment