Skip to content

Instantly share code, notes, and snippets.

@kjerk
Last active December 21, 2015 09:39
Show Gist options
  • Save kjerk/6286725 to your computer and use it in GitHub Desktop.
Save kjerk/6286725 to your computer and use it in GitHub Desktop.
HTTP Get function for powershell. Possible to to do a simple http GET request with parameters. Json formatting if Newtonsoft.Json.dll is found in your powershell profile directory and response type is Json. Supports string interpolation to parameterize request.
# Usage:
# Http-Get http://api.asite.com/getUser/45
# or string interpolation style:
# Http-Get "http://api.asite.com/{0}/{1}" getUser 45
function Http-Get
{
if($args.Length -lt 1)
{
"Invalid args."
return;
}
# Json.net formatting if Newtonsoft.Json.dll is found in your powershell profile directory
$formatJson = $false;
if([System.IO.File]::Exists("$([System.IO.Path]::GetDirectoryName($profile))\Newtonsoft.Json.dll"))
{
[System.Reflection.Assembly]::LoadFile("$([System.IO.Path]::GetDirectoryName($profile))\Newtonsoft.Json.dll");
$formatJson = $true;
}
$parms = New-Object System.Collections.ArrayList;
for($i=1; $i -lt $args.Length; $i++)
{ $parms.Add($args[$i]) | Out-Null; }
$req = [System.Net.WebRequest]::Create([String]::Format($args[0], [System.Object[]]$parms));
$req.Credentials = [System.Net.CredentialCache]::DefaultCredentials;
$resp = [System.Net.HttpWebResponse]$req.GetResponse();
Write-Host $resp.StatusDescription;
$sr = New-Object System.IO.StreamReader($resp.GetResponseStream());
$responseFromServer = $sr.ReadToEnd();
if($formatJson -eq $true -and $resp.ContentType.StartsWith("application/json"))
{
$jt = [Newtonsoft.Json.Linq.JToken]::Parse($responseFromServer);
Write-Host $jt.ToString([Newtonsoft.Json.Formatting]::Indented)
}
else
{
Write-Host $responseFromServer
}
$sr.Close();
$resp.Close();
}
@kjerk
Copy link
Author

kjerk commented Aug 20, 2013

Newtonsoft.Json.dll is from the Json.net package downloadable at http://json.codeplex.com/releases/view/107620. Just the bare .dll is required if you want json formatting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment