Monday 12 December 2011

Get-PortAndProtocolFromUrl.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     This script strips out a port and protocol number from a URL  
  4. .DESCRIPTION 
  5.     This script creates a regular expression reged then uses it to  
  6.     match against the URL to get the protocol and port. This is a 
  7.     re-write of the MSDN sample. 
  8. .NOTES 
  9.     File Name  : Get-PortAndProtocolFromUrl.ps1 
  10.     Author     : Thomas Lee - tfl@psp.co.uk 
  11.     Requires   : PowerShell Version 2.0 
  12. .LINK 
  13.     This script posted to: 
  14.         http://www.pshscripts.blogspot.com 
  15.     MSDN sample posted to: 
  16.         http://msdn.microsoft.com/en-us/library/63ew9az0.aspx 
  17. .EXAMPLE 
  18.     PowerShell> .\Get-PortAndProtocolFromUrl.ps1 
  19.     Port    : http 
  20.     Protocol: 8080    
  21. #> 
  22.  
  23. # Set URL 
  24. $url = "http://www.contoso.com:8080/letters/readme.html" 
  25.  
  26. # Create Regex, then match against the URL 
  27. $r = new-object System.Text.RegularExpressions.Regex "^(?<proto>\w+)://[^/]+?:(?<port>\d+)?/" 
  28. $m = $r.Match($url
  29.  
  30. # Print results 
  31. if ($m.Success) { 
  32.    "Port    : {0}" -f $M.groups["proto"].value 
  33.    "Protocol: {0}" -f $M.groups["port"].value 
  34.            

No comments: