Exploring the ConvertFrom-Markdown
Cmdlet in PowerShell
Welcome back to Wahman’s PowerShell Blog! 🎉
Today, we’re diving into a very handy cmdlet introduced in PowerShell 7 and above: ConvertFrom-Markdown
.
What does ConvertFrom-Markdown do?
According to Microsoft, it "Converts the contents of a string or a file to a MarkdownInfo object." In simpler terms, this cmdlet takes markdown content and converts it into a rich object that allows you to programmatically analyze and transform the structure or extract specific HTML-rendered fragments from it.
Why care about Markdown in PowerShell?
Markdown is everywhere: READMEs, documentation, changelogs, notes, etc. ConvertFrom-Markdown
can help you build tools that consume or transform that content.
🔰 Example 1: Convert a Simple Markdown String
$markdown = @"
# Hello World
This is a *simple* markdown example.
"@
$result = ConvertFrom-Markdown -Markdown $markdown
# Output the HTML version
$result.Html
This will return the rendered HTML for your markdown content. Perfect for building quick preview tools or transforming documentation.
🌐 Example 2: Read Markdown from a File
$filePath = "C:\Users\User\Documents\README.md"
$result = ConvertFrom-Markdown -Path $filePath
# View the HTML content
$result.Html
This example demonstrates loading a markdown file from disk and converting it to HTML for further use. Super useful for automating documentation pipelines!
🛠️ Example 3: Create a Markdown Viewer in Out-GridView
$markdown = @"
### Notes
- Item 1
- Item 2
- **Important:** Remember to commit your work!
"@
$result = ConvertFrom-Markdown -Markdown $markdown
[PSCustomObject]@{
HtmlContent = $result.Html
} | Out-GridView -Title "Markdown Preview"
This shows how you can visualize converted HTML in a GridView to create simple preview tools using the platform you already know—PowerShell!
🚀 Example 4: Extracting Headings from Markdown Programmatically
$markdown = Get-Content -Path "C:\Docs\project.doc.md" -Raw
$mdInfo = ConvertFrom-Markdown -Markdown $markdown
# Parse the markdown blocks for headings
$headings = $mdInfo.Tokens |
Where-Object { $_.Type -eq 'Heading' } |
Select-Object -Property Level, Text
$headings
Here we get more advanced! This showcases how you can programmatically inspect a markdown file and extract heading structures. This is great for building tools to validate documentation formats or for auto-generating tables of contents.
Wrapping Up
ConvertFrom-Markdown
adds awesome automation and parsing capabilities for markdown lovers and documentation ninjas. From generating previews to analyzing markdown structures, it opens many creative doors for PowerShell scripters.
Happy scripting, and I will see you in the next post! 🚀
Leave a Reply