Friday, August 21, 2015

PowerShell Tip : Shorten that URL (New-ShortUrl)

URL shortners are very popular in the social media feeds because of the fact that it helps you trim a long URL into am much shorter readable format and still redirect to the required page when accessed. There are many providers who can help you convert your URL into a more condensed format, some of them being,, etc.

If you are looking for an API in PowerShell to shorten your URL, you can use the API's provided by one of these providers and create a web request with the parameters to generate your shortened URL. So here's my simple and small module to invoke one of the provider's API ( to create a shortened URL.


function IsValidUri($url)
       $uri = $url -as [System.Uri]
       if($uri -eq $null)
              return $false

       $uri.AbsoluteUri -ne $null -and $uri.Scheme -match '[http|https]'

function New-ShortUrl
              [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
              [string] $Url
       if(-not (IsValidUri($Url)))
              throw "$($Url) is not a valid Uri"

       $tinyUrlApi = ''
       $response = Invoke-WebRequest ("{0}?url={1}" -f $tinyUrlApi, $Url)

Export-ModuleMember -Function New*

No comments: