Convert a list of urls to clickable HTML links with ConvertTo-HTML
I have a function below that will create an HTML table, but I want the values ββin my table to be hyperlinks.
Function MyFunction{
clear-host
$item=$null
$hash = $null #hashTable
$hash =@{"Google.com" = "www.google.com"; "Yahoo" = "www.yahoo.com";"My Directory" ="C:\Users\Public\Favorites" ;"MSN" = "www.msn.com"}
ForEach($item in @($hash.KEYS.GetEnumerator())){
$hash | Sort-Object -Property name
}
$hash.GetEnumerator() | sort -Property Name |Select-Object Name, Value | ConvertTo-HTML | Out-File .\Test.html
}
MyFunction
source to share
A little note before starting: ForEach
seems pointless as it just outputs a sorted table for every table element. So it is removed.
ConvertTo-HTML
by itself is great for creating a table with a PowerShell object, but we need hyperlinks. ConvertTo-HTML
supports computed properties, so at first it would be simple to create a formatted hyperlink.
ConvertTo-HTML -Property *,@{Label="Link";Expression={"<a href='$($_.Value)'>$($_.Name)</a>"}}
The little problem with this is ConvertTo-HTML
doing some kind of conversion on the sent string that cloudes our intent. Looking at the generated output file, we see the following for the Yahoo link:
<td><a href='www.yahoo.com'>Yahoo</a></td>
ConvertTo-HTML
made our browser friendly for the browser, which would be fine, but it gets in the way now. Reading Blog from PowerShell Journal describes this issue by decrypting the html before sending it to a file.
Function MyFunction{
clear-host
$hash = @{"Google.com" = "www.google.com"; "Yahoo" = "www.yahoo.com";"My Directory" ="C:\Users\Public\Favorites" ;"MSN" = "www.msn.com"}
$hash.GetEnumerator() | sort -Property Name | Select-Object Name, Value |
ConvertTo-HTML -Property *,@{Label="Link";Expression={"<a href='$($_.Value)'>$($_.Name)</a>"}}
}
$html = MyFunction
Add-Type -AssemblyName System.Web
[System.Web.HttpUtility]::HtmlDecode($html) | Out-File C:\temp\test.html
Usage [System.Web.HttpUtility]::HtmlDecode
converts values ββsuch as <
back to what we want. Look at the exit
Went to see if this was asked before and there is a similar answer: How to generate hyperlinks to .htm files in a directory in Powershell? ... It is handled differently, so the fence marks it as a duplicate.
source to share