PowerShell : Http Get/Post

This is another article in my on going learning/experimenting with PowerShell. This time I will show how you can use PowerShell to carry out REST operations such as GET/POST.

Now there may be some amongst you, who go why didn’t you just use WGet, which is a downloadable thing, and I could have indeed used that, except for the part that the machine I need to run this on, is so locked down that I can only use things that are already installed. So raw PowerShell it is

Here is the relevant PowerShell code, which allows 3 parameters to control the script

  • Target : The url
  • Verb : This is the http verb, GET, PUT etc
  • Content : This could be some content when doing a POST request for example

It just makes use of some very standard .NET classes namely WebRequest

    [string] $target,
    [string] $verb,      
    [string] $content
write-host "Http Url: $target"
write-host "Http Verb: $verb"
write-host "Http Content: $content"
$webRequest = [System.Net.WebRequest]::Create($target)
$encodedContent = [System.Text.Encoding]::UTF8.GetBytes($content)
$webRequest.Method = $verb
write-host "UTF8 Encoded Http Content: $content"
if($encodedContent.length -gt 0) {
    $webRequest.ContentLength = $encodedContent.length
    $requestStream = $webRequest.GetRequestStream()
    $requestStream.Write($encodedContent, 0, $encodedContent.length)
[System.Net.WebResponse] $resp = $webRequest.GetResponse();
if($resp -ne $null) 
    $rs = $resp.GetResponseStream();
    [System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
    [string] $results = $sr.ReadToEnd();
    return $results 
    exit ''

Here is an example usage (assuming the above script is saved as http.ps1 somewhere):

Http.ps1 -target “http://www.google.com” -verb “GET”

Which would give the following sort of output:


Anyway that’s it for now, hope this helps



  1. Hello Sacha, thank you very much for this part of code. It is hard to find any hint how to natively implement wget in PowerShell 2.0 environment.
    However the proposed code did not work properly for me as the web server (Apache 2.2.3) always returned blank $_POST array when using POST method with POST data in $content variable.
    After looking at native wget debug output comparing to PowerShell $webRequest object properties I realize that I need to set the property of $webRequest.Content type to ‘application/x-www-form-urlencoded”, as this Property is blank by default.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s