1

I need to do an API Get call on PowerShell 2.0 so I can't use the Invoke-RestMethod as it was introduced in version 3.0.

Anyone know how it can be done using PowerShell 2.0?

I have the following so far but don't know how to get the data from it. Preferably to a text file.

$request = [System.Net.WebRequest]::Create('http://www.google.com')

How do I extract data from it? If pasted into a browser it returns a simple text file with data in it.

Richard Slater
  • 6,313
  • 4
  • 53
  • 81
Deano
  • 155
  • 2
  • 3
  • 15
  • Isn't it a duplicate of [How to POST .json file in Powershell without Invoke-WebRequest?](http://stackoverflow.com/q/24436478/608772). I give the a function to call .NET classes. – JPBlanc May 10 '16 at 14:33

1 Answers1

1

What you are doing is calling into the .NET Framework, so you could convert the code samples on the MSDN documentation to PowerShell.

However, when using PowerShell 2.0 I find it easier to use the DownloadString method of WebClient:

$client = New-Object System.Net.WebClient
$data = $client.DownloadString('https://api.mysite.com/resource')
Set-Content -Value $data -Path 'resource.txt'

If the output is an XML document you can simply cast the returned string to XML:

$xmlData = [xml]$data

If the output is JSON then you can use the functions from PowerShell 2.0 ConvertFrom-Json and ConvertTo-Json implementation.

Community
  • 1
  • 1
Richard Slater
  • 6,313
  • 4
  • 53
  • 81
  • Hi Richard, Great help. I am able to get the data out. I cannot convert the data into xml - i get the following error - "There are multiple root elements. Line 2, position 2." – Deano May 10 '16 at 15:08
  • That's probably because the API you are calling is adding in some extra data, perhaps post an example as a new question, be sure to [run a search first though](http://stackoverflow.com/search?q=There+are+multiple+root+elements.+Line+2%2C+position+2). – Richard Slater May 10 '16 at 15:12
  • Hi Richard, a valid point has been made to me and need to make an amendment. The API for the host maybe down or not exist. Therefore how would I add logic to test the API call first. Any ideas for powershell 2.0? Thanks – Deano May 17 '16 at 14:18
  • I did Richard, resolved using Try catch method. See http://stackoverflow.com/questions/37279103/test-webclient-api-call – Deano May 18 '16 at 09:38