regexpowershellmarkdown

Trying to use regex to replace text in a powershell script


I have a string that includes markdown text and I'm trying to convert it to html syntax. When I test in any regex tester, my code is good, but the powershell replace operator, just won't do it. I think I'm missing something, but not sure what.

Does anyone have any ideas?

Example:

$message = "This is a test: [Latest Release Notes](https://learn.microsoft.com/en-us/azure/devops/release-notes/2023/sprint-218-update)"
$markdownLinkRegex = "/\[([^\[\]]+)\]\(([^\(\)]+)\)/g"
# have tried both of these options below
$htmlmessage = $message -replace ([regex]::Escape($markdownLinkRegex)), "<a href='$2'>$1</a>"
$htmlmessage = $message -replace $markdownLinkRegex, "<a href='$2'>$1</a>"

I have tried adding extra '\' into the regex string, but that made it worse.

I am expecting to see this result:

$htmlmessage = "This is a test: <a href='https://learn.microsoft.com/en-us/azure/devops/release-notes/2023/sprint-218-update'>Latest Release Notes</a>"

Solution

  • The Microsoft.PowerShell.Utility Module comes with the ConvertFrom-Markdown cmdlet on PowerShell 7.2+ and it uses the markdig library to parse markdown files and strings.

    Converting your string to its HTML representation is as simple as:

    $message = "This is a test: [Latest Release Notes](https://learn.microsoft.com/en-us/azure/devops/release-notes/2023/sprint-218-update)"
    (ConvertFrom-Markdown -InputObject $message).Html