Last active
December 21, 2015 09:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.