1
votes

I fairly new to powershell, so I'm hoping someone may be able to help me out! I am trying to parse version numbers out of a webrequest and not sure of the best way to go about it. Basically, I'm using a website to store a package, and want to be able to call to a URL and download the file. The URL unfortunately only downloads the latest package, so I need to specify the version in the URL.

The goal is to pull the version list from the site, and then take the version number, and loop through, appending it to the download url for each version.

Currently to get the version, I have the following:

$api = 'http://localhost/package/NameOfProject/Packages()? 
$format=json&$filter=id%20eq%20%27NameOfPackaget%27%20&$select=Version'

$response = Invoke-WebRequest -Uri $api | select-object Content

This will output

Content                                                                    
-------                                                                    
{"d":{"results":[{"Version":"3.3.14.2"},{"Version":"3.3.14.5"}],"count":0}}

Basically, I want it to just give me the versions (3.3.14.2), so that I can then use Invoke-WebRequest again with an -OutFile tag to save the files.

I'm probably approaching this in a completely incorrect way, so any guidance is appreciated!

2

2 Answers

2
votes

beatcracker's helpful answer shows how to solve your problem with the Invoke-WebRequest cmdlet.

However, the Invoke-RestMethod cmdlet offers a simpler solution, because it automatically parses JSON text into objects ([pscustomobject] instances) that you can drill into with dot notation:

(Invoke-RestMethod $api).d.results.Version # add `[0]` to only extract the first version

If you need to exclude versions that match a pattern, such as those that have a --based suffix (e.g., 3.3.14.2-Test)):

@((Invoke-RestMethod $api).d.results.Version) -notmatch '-'
2
votes

You need to convert JSON in the Content property to the object and get all values of the the Version properties:

($response | ConvertFrom-Json).d.results.Version

Result:

3.3.14.2
3.3.14.5