Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of URLs into clickable HTML links using ConvertTo-HTML

Tags:

powershell

I have the function below that will create an HTML table however I want the values in my table to 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
like image 959
Naim R. Avatar asked Dec 26 '14 04:12

Naim R.


1 Answers

Small side note before we start: The ForEach seems pointless as it just outputs the sorted table for each element in the table. So that gets removed.

ConvertTo-HTML on its own is great for making table with PowerShell object but was we need is hyperlinks instead. ConvertTo-HTML does support calculated properties so at first it would seem easy to just make a formatted hyperlink.

ConvertTo-HTML -Property *,@{Label="Link";Expression={"<a href='$($_.Value)'>$($_.Name)</a>"}}

The small issue with that is ConvertTo-Html does some conversion on the string being sent to it which obfuscates our intention. Looking in the output file that is created we see the following for the Yahoo link:

<td>&lt;a href=&#39;www.yahoo.com&#39;&gt;Yahoo&lt;/a&gt;</td>

ConvertTo-Html made our text browser friendly which would be nice normally but hinders us now. Reading a blog from PowerShell Magazine covers this issue by decoding the html before it is send to 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

Using [System.Web.HttpUtility]::HtmlDecode converts values like &lt; back to what we want them to be. Have a look at the output

Output

Went looking to see if this has been asked before and there is a similar answer: How to generate hyperlinks to .htm files in a directory in Powershell?. It is handled in a different way so im on the fence about marking this as a duplicate.

like image 71
Matt Avatar answered Sep 28 '22 04:09

Matt