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.

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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."
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.
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
I did Richard, resolved using Try catch method. See stackoverflow.com/questions/37279103/test-webclient-api-call

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.