Last active
April 9, 2025 14:57
-
-
Save tcartwright/1e6b471d6df69f445421ac05c04ba22d to your computer and use it in GitHub Desktop.
POWERSHELL: Generate markdown from query
This file contains 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
Clear-Host | |
# UPDATE QUERY / SERVER / DB | |
$serverInstance = "..." | |
$database = "..." | |
$query = " | |
SELECT * FROM sys.tables | |
" | |
# UPDATE QUERY / SERVER / DB | |
$lineEnd = [Environment]::NewLine | |
$skipHeaders = "RowError", "Table", "ItemArray", "HasErrors", "RowState" | |
$results = Invoke-Sqlcmd -Query $query -ServerInstance $serverInstance -Database $database -Encrypt Optional | |
$markdown = "" | |
if ($results.Count -gt 0) { | |
$headers = $results[0].PSObject.Properties.Name | Where-Object { $skipHeaders -inotcontains $_ } | |
$markdown += "| **" + ($headers -join "** | **") + "** |$lineEnd" | |
$sep = "| " | |
foreach($header in $headers ) { | |
## $header.Length + 4 for the bolding of the headers | |
$markdown += $sep + ("-" * ($header.Length + 4)) | |
$sep = " | " | |
} | |
$markdown += " |$lineEnd" | |
foreach ($item in $results) { | |
# make sure to handle nulls, and still output a | | column for them | |
$row = foreach ($header in $headers) { "$($item.$header) ".Trim() } | |
$markdown += "| " + ($row -join " | ") + " |$lineEnd" | |
} | |
} else { | |
$markdown = "No results found." | |
} | |
$markdown | Out-Host | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment