Skip to content

Instantly share code, notes, and snippets.

@Matticusau
Forked from BenNeise/ConvertTo-Markdown.ps1
Last active February 9, 2022 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Matticusau/49943eb19efd54783966449bde53e9db to your computer and use it in GitHub Desktop.
Save Matticusau/49943eb19efd54783966449bde53e9db 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)
.EXAMPLE
Invoke-ScriptAnalyzer -Path C:\MyScript.ps1 | Select-Object -Property RuleName,Line,Severity,Message | `
ConvertTo-Markdown | Out-File C:\MyScript.ps1.md
Converts the output of PSScriptAnalyzer for a given script to a Markdown report using selected properties
#>
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 | ForEach-Object {
# get the value to avoid (null value object errors)
$value = $null;
if ($value -ne $_.Value)
{
$value = $_.Value.ToString().Length;
}
# verify if we need to add the value to the hash table
if(-not $columns.ContainsKey($_.Name) -or $columns[$_.Name] -lt $value.Length) {
$columns[$_.Name] = $value;
}
}
}
}
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 ' | '
}
}
}
@Matticusau
Copy link
Author

This gist is forked from GuruAnt/ConvertTo-Markdown.ps1 and includes the following improvements:

  1. Fixed the null object reference error when the value = $null
  2. A couple of aliases changed to full cmdlet name for best practices
  3. Extra Example for how I use this with PSScriptAnalyzer

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