0

What is the equivalent to Invoke-WebRequest function in PowerShell Version 2. This is what I am trying to doing with my function as I cannot upgrade to PowerShell 4 because I am working on Windows Server 2003.

Invoke-WebRequest $uri -Body ($baseMessage | ConvertTo-Json -Compress) -Method Post -ContentType "application/json" 

Thank you

Matt
  • 45,022
  • 8
  • 78
  • 119

2 Answers2

3
$Web = New-Object System.Net.WebClient
$Web.OpenRead($url)
$PageContents = New-Object System.IO.StreamReader($Web)
$PageContents.ReadToEnd()

If you're looking to submit JSON data you can use this instead:

$Encoding = [System.Text.Encoding]::GetEncoding("ASCII")
$postArray = $Encoding.GetBytes($json)
$Web = [System.Net.WebRequest]::Create($url)
$Web.Method = "POST"
$Web.Timeout = 10000;
$Stream = $Web.GetRequestStream()
$Stream.Write($postArray, 0, $postArray.Length)
$Web.GetResponse()

https://msdn.microsoft.com/en-us/library/System.Net.WebClient_methods(v=vs.80).aspx

Found another similar question on stackoverflow:

PowerShell WebRequest POST

Community
  • 1
  • 1
Nathan Rice
  • 3,091
  • 1
  • 20
  • 30
  • This doesn't quite work. Exception that says " Calling OpenWrite with "2" arguments" –  Apr 24 '15 at 18:59
  • Can you tell me exactly how my statement would look using this ? Invoke-WebRequest requires attributes such as -Body, -ContentType, and -Method –  Apr 24 '15 at 19:57
1

You can use System.Net.Webrequest .NET class in powershell v2 instead.

See this example from one of my powershell answers: Powershell - View Website Source Information

And also answer to this shows how to set json content type, albeit in C# How to get json response using system.net.webrequest in c#?

Community
  • 1
  • 1
Graham Gold
  • 2,435
  • 2
  • 25
  • 34
  • Can you tell me exactly how my statement would look using this ? Invoke-WebRequest requires attributes such as -Body, -ContentType, and -Method –  Apr 24 '15 at 19:42
  • If you check the msdn reference for System.Net.Webrequest you will see it has the properties you need : https://msdn.microsoft.com/en-us/library/system.net.webrequest%28v=vs.110%29.aspx – Graham Gold Apr 24 '15 at 21:24