The following PowerShell code will return a shortened URL from a long URL using the Google link shortening URL API. Contrast this code with the code for Bit.ly. There are couple differences:
1. Calling the Google API is done with a POST. With Bit.ly it is a GET.
2. I’ve included an interactive prompt in the code below, that will get the long URL from the command line. Once the shortened link is printed, you can paste it to the clipboard. (Or…better yet, avoid mousing around, and pipe the result to the clipboard using the clip.exe utility
# Generate shortened URL using the Google API
# First time set up:
# * Log in with your Google login name and password
# * Go to the Google Developer Console at:
# * https://console.developers.google.com/project
# * Create a new project.
# * Obtain an application key.(Don’t worry about oAuth)
# * Be sure that you allow requests from
# * “all IP addresses”
$APIKey=”xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
# Hard coded long link below,or comment out line 17 and
# uncomment 20-23 for an interactive command line
#######################################################
# Paste in the URL that you want to shorten here.
$LongURL=”http://twitter.com”
#
#######################################################
# $Instructions = “You can paste a long URL into the`
# command line by right-clicking the mouse.`n”
# $Instructions
# $LongURL= Read-Host “Enter or Paste in the Long URL”
#######################################################
#Convert the Long URL to a JSON key/value
$LongHash=@{“longUrl”=$LongURL}
$MyLongURI = $LongHash | ConvertTo-Json
# Make the API call
$MyShortURL=Invoke-RestMethod `
-Uri https://www.googleapis.com/urlshortener/v1/url?key=$APIKey `
-Body $MyLongURI `
-ContentType application/json `
-Method Post
# Print out the shortened URL
$LongURL
$MyShortURL.id