ConvertFrom-Markdown: Parse Markdown Content into Structured Objects in PowerShell
Welcome back to Wahmans Powershell blog! Today, we’re diving into the ConvertFrom-Markdown cmdlet — a cool feature in PowerShell that allows you to convert the contents of a Markdown-formatted string or file into a MarkdownInfo object.
What does ConvertFrom-Markdown do?
According to Microsoft:
ConvertFrom-Markdown converts the contents of a string or a file to a
MarkdownInfoobject.
Why is that useful? If you’ve ever wanted to parse Markdown files like README.md or process Markdown elements programmatically within PowerShell — this cmdlet is your new best friend!
Examples from Beginner to Advanced
Example 1: Basic Markdown String
This basic example demonstrates how to convert a simple Markdown string into an object:
$markdown = """
# Hello World
This is a sample markdown string.
- Item 1
- Item 2
"""
$result = ConvertFrom-Markdown -Markdown $markdown
$result.Html
This will output the HTML equivalent of the markdown.
Example 2: Converting a Markdown File
Let’s say you have a README.md file. You can easily convert it like this:
$result = ConvertFrom-Markdown -Path "C:\Projects\MyRepo\README.md"
# Output the HTML content
$result.Html
This is useful if you’re building tools to display or validate project documentation.
Example 3: Extracting Headers from Markdown
Let’s parse the Markdown and extract just the headings. This is great for generating documentation indexes or tables of content!
$markdown = Get-Content -Path ".\guide.md" -Raw
$parsed = ConvertFrom-Markdown -Markdown $markdown
# Regex to extract , , tags from HTML
$parsed.Html -match "<h[1-6]>(.*?)</h[1-6]>" | ForEach-Object {
[regex]::Matches($_, "<h(?<level>[1-6])>(?<text>.*?)</h[1-6]>") | ForEach-Object {
"Level $($_.Groups['level'].Value): $($_.Groups['text'].Value)"
}
}
This will give you lines like:
Level 1: Introduction
Level 2: Installation
Level 2: Usage
Example 4: Integrating with a Static Site Generator
Advanced usage — let’s say you’re building a simple static site generator in PowerShell. You can read Markdown files from a folder and convert them to HTML pages:
$sourceDir = ".\markdown"
$outputDir = ".\html"
Get-ChildItem -Path $sourceDir -Filter *.md | ForEach-Object {
$content = Get-Content -Path $_.FullName -Raw
$html = ConvertFrom-Markdown -Markdown $content
$outFile = Join-Path $outputDir ($_.BaseName + ".html")
$htmlContent = @"
$($_.BaseName)
$html
"@
Set-Content -Path $outFile -Value $htmlContent
}
This allows you to quickly transform markdown pages into usable HTML files — all within PowerShell!
Conclusion
Whether you’re a beginner or scripting something more complex, ConvertFrom-Markdown has a solid place in your PowerShell toolkit. Markdown is everywhere — from GitHub READMEs to documentation — and now with PowerShell, you can interact with it programmatically and easily.
Happy scripting, and I will see you in the next post!
Leave a Reply