Skip to content

Instantly share code, notes, and snippets.

@lholman
Created January 15, 2014 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lholman/8436222 to your computer and use it in GitHub Desktop.
Save lholman/8436222 to your computer and use it in GitHub Desktop.
Performs an HTTP GET for a supplied URL, optionally using a supplied hostname and also optionally returning the HTTP statuscode as opposed to response content
function Get-Url{
<#
.SYNOPSIS
Performs an HTTP GET for a supplied URL
.DESCRIPTION
Performs an HTTP GET for a supplied URL, optionally using a supplied hostname and also optionally returning the HTTP statuscode as opposed to response content
.NOTES
Requirements: Copy this module to any location found in $env:PSModulePath
.PARAMETER url
Required. The URL to GET
.PARAMETER hostName
Optional. The hostname to use in the HttpWebRequest
.PARAMETER returnStatusCodeOnly
Optional. Set to $true to just return the HTTP statuscode. By default this is $false and the response content is returned
.EXAMPLE
Import-Module Get-Url
Import the module
.EXAMPLE
Get-Command -Module Get-Url
List available functions
.EXAMPLE
Get-Url -url "http://google.com"
Execute the module
#>
[cmdletbinding()]
Param(
[Parameter(
Position = 0,
Mandatory = $True )]
[string]$url,
[Parameter(
Position = 1,
Mandatory = $False )]
[string]$hostName,
[Parameter(
Position = 2,
Mandatory = $False )]
[boolean]$returnStatusCodeOnly
)
Begin {
$DebugPreference = "Continue"
}
Process {
Try
{
Write-Debug "url: $url"
Write-Debug "hostName: $hostName"
$request = [System.Net.HttpWebRequest]::Create($url);
#$request.Timeout = $timeout;
if ($hostName -ne "")
{
$request.Host = $hostName
}
$response = $request.GetResponse();
if ($returnStatusCodeOnly -eq $True)
{
return [int][System.Net.HttpStatusCode]$response.StatusCode
} else {
$reader = new-object System.IO.StreamReader($response.GetResponseStream());
$text = $reader.ReadToEnd();
$reader.Close();
return $text;
}
}
catch [Exception] {
throw "Error: W`r`n $_.Exception.ToString()"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment