Welcome!

PHP Authors: Liz McMillan, Carmen Gonzalez, Hovhannes Avoyan, Lori MacVittie, Trevor Parsons

Blog Feed Post

Shrink-Url – Use PowerShell To Shrink Your Urls

poshShrinkShrinking your Url’s is all the rage nowadays.  If you are on Twitter, then odds are you have used one.  Despite CodingHorror’s distaste for them in his recent blog post on Url Shorteners: Destroying the Web since 2002, they are a fact of life when we live in a world of 140 character status updates.

So what’s a URL shrinking service anyway?  Well, to put it simply, you supply them with a URL, they then supply you with a shorter URL containing a lookup “key”.  When future requests are made to this shorter URL, connections are routed to that services website where they convert the short URL to the original URL and issue a HTTP Redirect back to your browser to send you off to the original long url website.

So, what’s a guy, or gal, to do if they want to set their status programmatically on Twitter, Facebook, FriendFeed, or the other gazillion social networking sites out there today and need to post a very long URL?  Most of these shrinking services offer API’s to access their “shrinking” services so it’s just a matter of digging into the various APIs to get them implemented.  In my original PowerShell Twitter library PoshTweet, I included support for a couple for shrinking URL’s through a couple of shrinking services but I figured it would be good to separate that functionality out into it’s own library. 

So, here’s my first stab at a generic URL shortening library for PowerShell.  I’ve included the following services:

Some of these services have advanced features such as statistical reporting on all your submitted links.  Those services require users to create accounts and register for API keys.  Bit.ly is one of them, so if you want to use that service, you will have to supply this script with your bit.ly username and API key with the Set-BitlyServiceInfo function.

So, here’s the script, hope you all enjoy!

 

   1: param(
   2:   [string]$longurl = $null,
   3:   [string]$provider = "tinyurl"
   4: );
   5:  
   6: $script:DIGG_APPKEY = "https://devcentral.f5.com/PoshShrink";
   7: $script:BITLY_LOGIN = "";
   8: $script:BITLY_KEY = "";
   9:  
  10: #----------------------------------------------------------------------------
  11: # function Set-BitlyServiceInfo
  12: #----------------------------------------------------------------------------
  13: function Set-BitlyServiceInfo()
  14: {
  15:   param(
  16:     [string]$login = $null,
  17:     [string]$key = $null
  18:   );
  19:   if ( $login -and $key )
  20:   {
  21:     $script:BITLY_LOGIN = $login;
  22:     $script:BITLY_KEY = $key;
  23:   }
  24:   else
  25:   {
  26:     Write-Error "Usage: Set-BitlyServiceInfo -login login -key key";
  27:   }
  28: }
  29:  
  30: #----------------------------------------------------------------------------
  31: # function Shrink-Url
  32: #----------------------------------------------------------------------------
  33: function Shrink-Url()
  34: {
  35:   param(
  36:     [string]$longurl = $null,
  37:     [string]$provider = "tinyurl"
  38:   );
  39:   
  40:   $shorturl = $null;
  41:   if ( $longurl )
  42:   {
  43:     switch ($provider.ToLower())
  44:     {
  45:       "is.gd" {
  46:         $shorturl = Execute-HTTPGetCommand "http://is.gd/api.php?longurl=$longurl";
  47:       }
  48:       "tinyurl" {
  49:         $shorturl = Execute-HTTPGetCommand "http://tinyurl.com/api-create.php?url=$longurl";
  50:       }
  51:       "snurl" {
  52:         $shorturl = Execute-HTTPGetCommand "http://snipr.com/site/snip?r=simple&link=$longurl";
  53:       }
  54:       "digg" {
  55:         [xml]$results = Execute-HTTPGetCommand `
  56:           "http://services.digg.com/url/short/create?url=${longurl}&appkey=${script:DIGG_APPKEY}";
  57:         $shorturl = $results.shorturls.shorturl.short_url;
  58:       }
  59:       "tr.im" {
  60:         [xml]$results = Execute-HTTPGetCommand "http://api.tr.im/api/trim_url.xml?url=$longurl";
  61:         $shorturl = $results.trim.url;
  62:       }
  63:       "bit.ly" {
  64:         if ( !$BITLY_LOGIN -or !$BITLY_KEY )
  65:         {
  66:           Write-Error "ERROR: You must configure your bit.ly LOGIN and APIKEY!"
  67:           exit;
  68:         }
  69:         else
  70:         {
  71:           $results = Execute-HTTPGetCommand `
  72:             "http://api.bit.ly/shorten?version=2.0.1&longUrl=$longurl&login=$script:BITLY_LOGIN&apiKey=$script:BITLY_KEY";
  73:           $shorturl = $results.Split("`n")[7].Split("""")[3];
  74:         }
  75:       }
  76:       default {
  77:         $shorturl = Execute-HTTPGetCommand "http://tinyurl.com/api-create.php?url=$longurl";
  78:       }
  79:     }
  80:   }
  81:   else
  82:   {
  83:     Write-Host "ERROR: Usage: Shrink-Url -longurl http://www.foo.com";
  84:   }
  85:   $shorturl;
  86: }
  87:  
  88: #----------------------------------------------------------------------------
  89: # function Execute-HTTPGetCommand
  90: #----------------------------------------------------------------------------
  91: function Execute-HTTPGetCommand()
  92: {
  93:   param([string] $url = $null);
  94:   
  95:   $user_agent = "PoshShrink";
  96:   
  97:   if ( $url )
  98:   {
  99:     $request = [System.Net.HttpWebRequest]::Create($url);
 100:     $request.UserAgent = $user_agent;
 101:     $request.Credentials = [System.Net.CredentialCache]::DefaultCredentials;
 102:     if ( $request.Proxy )
 103:     {
 104:       $request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials;
 105:     }
 106:     $response = $request.GetResponse();
 107:     $rs = $response.GetResponseStream();
 108:     [System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs;
 109:     $sr.ReadToEnd();
 110:   }
 111: }
 112:  
 113: Shrink-Url -longurl $longurl -provider $provider;

 

You can download the full contents for this script here: Shrink-Url.ps1

Read the original blog entry...

More Stories By Joe Pruitt

Joe Pruitt is a Principal Strategic Architect at F5 Networks working with Network and Software Architects to allow them to build network intelligence into their applications.

@ThingsExpo Stories
Financial Technology has become a topic of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 20th Cloud Expo at the Javits Center in New York, June 6-8, 2017, will find fresh new content in a new track called FinTech.
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 20th Cloud Expo, which will take place on June 6-8, 2017 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 add...
The age of Digital Disruption is evolving into the next era – Digital Cohesion, an age in which applications securely self-assemble and deliver predictive services that continuously adapt to user behavior. Information from devices, sensors and applications around us will drive services seamlessly across mobile and fixed devices/infrastructure. This evolution is happening now in software defined services and secure networking. Four key drivers – Performance, Economics, Interoperability and Trust ...
Grape Up is a software company, specialized in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the USA and Europe, we work with a variety of customers from emerging startups to Fortune 1000 companies.
Cybersecurity is a critical component of software development in many industries including medical devices. However, code is not always written to be robust or secure from the unknown or the unexpected. This gap can make medical devices susceptible to cybersecurity attacks ranging from compromised personal health information to life-sustaining treatment. In his session at @ThingsExpo, Clark Fortney, Software Engineer at Battelle, will discuss how programming oversight using key methods can incre...
Multiple data types are pouring into IoT deployments. Data is coming in small packages as well as enormous files and data streams of many sizes. Widespread use of mobile devices adds to the total. In this power panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists will look at the tools and environments that are being put to use in IoT deployments, as well as the team skills a modern enterprise IT shop needs to keep things running, get a handle on all this data, and deli...
SYS-CON Events announced today that Grape Up will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct. 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Grape Up is a software company specializing in cloud native application development and professional services related to Cloud Foundry PaaS. With five expert teams that operate in various sectors of the market across the U.S. and Europe, Grape Up works with a variety of customers from emergi...
The Internet of Things is clearly many things: data collection and analytics, wearables, Smart Grids and Smart Cities, the Industrial Internet, and more. Cool platforms like Arduino, Raspberry Pi, Intel's Galileo and Edison, and a diverse world of sensors are making the IoT a great toy box for developers in all these areas. In this Power Panel at @ThingsExpo, moderated by Conference Chair Roger Strukhoff, panelists discussed what things are the most important, which will have the most profound e...
@ThingsExpo has been named the Most Influential ‘Smart Cities - IIoT' Account and @BigDataExpo has been named fourteenth by Right Relevance (RR), which provides curated information and intelligence on approximately 50,000 topics. In addition, Right Relevance provides an Insights offering that combines the above Topics and Influencers information with real time conversations to provide actionable intelligence with visualizations to enable decision making. The Insights service is applicable to eve...
SYS-CON Events announced today that SoftLayer, an IBM Company, has been named “Gold Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2016, at the Javits Center in New York, New York. SoftLayer, an IBM Company, provides cloud infrastructure as a service from a growing number of data centers and network points of presence around the world. SoftLayer’s customers range from Web startups to global enterprises.
SYS-CON Events announced today that Hitachi, the leading provider the Internet of Things and Digital Transformation, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Hitachi Data Systems, a wholly owned subsidiary of Hitachi, Ltd., offers an integrated portfolio of services and solutions that enable digital transformation through enhanced data management, governance, mobility and analytics. We help globa...
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
Web Real-Time Communication APIs have quickly revolutionized what browsers are capable of. In addition to video and audio streams, we can now bi-directionally send arbitrary data over WebRTC's PeerConnection Data Channels. With the advent of Progressive Web Apps and new hardware APIs such as WebBluetooh and WebUSB, we can finally enable users to stitch together the Internet of Things directly from their browsers while communicating privately and securely in a decentralized way.
Data is an unusual currency; it is not restricted by the same transactional limitations as money or people. In fact, the more that you leverage your data across multiple business use cases, the more valuable it becomes to the organization. And the same can be said about the organization’s analytics. In his session at 19th Cloud Expo, Bill Schmarzo, CTO for the Big Data Practice at Dell EMC, introduced a methodology for capturing, enriching and sharing data (and analytics) across the organization...
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in compute, storage and networking technologies, will exhibit at SYS-CON's 20th International Cloud Expo®, which will take place on June 6-8, 2017, at the Javits Center in New York City, NY. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology, is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/...
Amazon has gradually rolled out parts of its IoT offerings in the last year, but these are just the tip of the iceberg. In addition to optimizing their back-end AWS offerings, Amazon is laying the ground work to be a major force in IoT – especially in the connected home and office. Amazon is extending its reach by building on its dominant Cloud IoT platform, its Dash Button strategy, recently announced Replenishment Services, the Echo/Alexa voice recognition control platform, the 6-7 strategic...
SYS-CON Events announced today that DatacenterDynamics has been named “Media Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY. DatacenterDynamics is a brand of DCD Group, a global B2B media and publishing company that develops products to help senior professionals in the world's most ICT dependent organizations make risk-based infrastructure and capacity decisions.
20th Cloud Expo, taking place June 6-8, 2017, at the Javits Center in New York City, NY, will feature technical sessions from a rock star conference faculty and the leading industry players in the world. Cloud computing is now being embraced by a majority of enterprises of all sizes. Yesterday's debate about public vs. private has transformed into the reality of hybrid cloud: a recent survey shows that 74% of enterprises have a hybrid cloud strategy.
Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more business becomes digital the more stakeholders are interested in this data including how it relates to business. Some of these people have never used a monitoring tool before. They have a question on their mind like “How is my application doing” but no id...
The buzz continues for cloud, data analytics and the Internet of Things (IoT) and their collective impact across all industries. But a new conversation is emerging - how do companies use industry disruption and technology enablers to lead in markets undergoing change, uncertainty and ambiguity? Organizations of all sizes need to evolve and transform, often under massive pressure, as industry lines blur and merge and traditional business models are assaulted and turned upside down. In this new da...