PowerShell – Convert To Weblink

During a recent project I was presented with a long text that was supposed to be emailed to administrative staff. The problem with the text is that it contained links to webpages. And since it was delivered as a text those links didn’t not get converted to HTML formattedformated links in the email.

The Input

The input can be any text that is delivered as a string.
For example:

$InputText = @"
This is meaningful text that someone important has written

A bit down there is a link in the text to http://wwww.viamonstra.com

Viamonstra team

The Script

Created:     2016-09-22
Version:     1.0
Author :     Peter Lofgren
Twitter:     @LofgrenPeter
Blog   :     https://syscenramblings.wordpress.com

This script is provided "AS IS" with no warranties, confers no rights and
is not supported by the author
  Change DNS Client address on a computer
  Sets new DNS client ip address on one or more computers
  Invoke-DnsServersChange.ps1 -ComputerName Server01.corp.viamonstra.com -PrimaryDns -SecondaryDNS
  Invoke-DnsServersChange.ps1 -ComputerName Server01.corp.viamonstra.com,Server02.corp.viamonstra.com -PrimaryDns -SecondaryDNS
  Invoke-DnsServersChange.ps1 -ComputerName C:\Servers.txt -PrimaryDns -SecondaryDNS

Function Convert-Weblink($InputText) {
  $regex = "(ht|f)tp(s?)\:\/\/(([a-zA-Z0-9\-\._]+(\.[a-zA-Z0-9\-\._]+)+)|localhost)(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?([\d\w\.\/\%\+\-\=\&amp;\?\:\\\&quot;\'\,\|\~\;]*)"
  $Matches = (Select-String -InputObject $InputText -Pattern $regex -AllMatches).Matches | select -Unique
  foreach ($Match in $Matches) {
    $InputText = $InputText -replace [regex]::Escape($Match.Value),"<a href=$($Match.value)>$($Match.value)</a>"
  Return $InputText

The Output

Using the example input text above the output would look something like this and you can the use that to build a webpage, send a HTML formatted email or any other HTML scenario you can think of.

This is meaningful text that someone important has written

A bit down there is a link in the text to <a href=http://wwww.viamonstra.com>http://wwww.viamonstra.com</a&gt;

Viamonstra team
<a href=http://www.viamonstra.com>http://www.viamonstra.com</a&gt;


Hopefully this helps you out and let me know if you find any issues!



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s