Advertisement
cwprogram

Test-HttpGet Function

Jul 14th, 2011
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .SYNOPSIS
  3. Check to see if a URL request returns data
  4.  
  5. .DESCRIPTION
  6. This function uses a WebClient object which attempts to download
  7. data from a given URL. This test will fail if there is an exception,
  8. or if the data returned is empty.
  9.  
  10. .OUTPUTS
  11. PSObject. returns a custom object with the following properties:
  12. Pass - true/false Whether or not the test passed
  13. Exception - The exception that occurred (Only if Pass = false)
  14. ExceptionType - The type of exception that occurred (Only if Pass = false)
  15.  
  16. .INPUTS
  17. The Test-HttpGet function does not accept piped input
  18.  
  19. .LINK
  20. http://msdn.microsoft.com/en-us/library/system.net.webexception(v=vs.80).aspx
  21.  
  22. .EXAMPLE
  23. PS [LAPTOP-TOSHIBA] >Test-HttpGet -url "http://msdn.microsoft.com" | Format-List
  24.  
  25. Pass : True
  26.  
  27. -- The GET request succeeded
  28.  
  29. .EXAMPLE
  30. PS [LAPTOP-TOSHIBA] >Test-HttpGet -url "https://msdn.microsoft.com" | Format-List
  31.  
  32. Pass : True
  33.  
  34. -- HTTPS works as well
  35.  
  36. .EXAMPLE
  37. PS [LAPTOP-TOSHIBA] >Test-HttpGet -url "http://false.whereisthis.net" | Format-List
  38.  
  39. Pass          : False
  40. Exception     : The remote name could not be resolved: 'false.whereisthis.net'
  41. ExceptionType : Web Exception
  42.  
  43. -- The GET request false because the site does not exist
  44. #>
  45. function Test-HttpGet {
  46.     param(
  47.         [parameter(Mandatory=$true)]
  48.         [ValidateNotNullOrEmpty()]
  49.         [string]
  50.         $url
  51.     )
  52.    
  53.     try {
  54.         $data = (new-object System.Net.WebClient).DownloadString($url)
  55.         if(!$data) {
  56.             return New-Object PSObject -Property @{
  57.                 Pass=$false;
  58.                 Exception="No data was returned";
  59.                 ExceptionType="Data Validation";
  60.             }
  61.         }
  62.         else {
  63.             return New-Object PSObject -Property @{
  64.                 Pass=$true;
  65.             }
  66.         }
  67.     }
  68.     catch [System.Net.WebException] {
  69.         return New-Object PSObject -Property @{
  70.             Pass=$false;
  71.             Exception=$_;
  72.             ExceptionType="Web Exception";
  73.         }        
  74.     }    
  75.     catch {
  76.         return New-Object PSObject -Property @{
  77.             Pass=$false;
  78.             Exception=$_;
  79.             ExceptionType="General";
  80.         }    
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement