2
$path = "https://api.statuspage.io/v1/pages/$page_id/$endpoint"
$req  = Invoke-WebRequest -Uri $path -Method GET

This request returns an array of objects (50+). I can see this by running a Write-Host $req

Problem is, when I try something like

foreach($i in $req) {
  Write-Host $i
}

I am given the entire object. And similarly, if I run Write-Host $req.length I am given 1. What gives?

Additionally, there is no way to run something like

$global:res = ConvertFrom-Json $req

Because it's already being returned as a JSON

8
  • what do you get from $Req.GetType() or from $Req | Get-Member? Commented Nov 13, 2020 at 14:45
  • GetType() gives me Microsoft.PowerShell.Commands.HtmlWebResponseObject and Get-Member gives me a bynch of stuff void...bool..int..type.. etc Commented Nov 13, 2020 at 14:49
  • What if you run $singleReq = $req | select-object -first 1; $singleReq.GetType() ? That is a quick way to convert an array response to get the first item (or same item if not an array). Also, it's possible that powershell is following links...try using -UseBasicParsing to keep it from parsing HTML Commented Nov 13, 2020 at 15:15
  • It gives me this: Microsoft.PowerShell.Commands.HtmlWebResponseObject Commented Nov 13, 2020 at 15:19
  • 1
    Try $req.Content | ConvertFrom-Json Commented Nov 13, 2020 at 15:23

1 Answer 1

2

If your intent is to parse the JSON text into (nested) objects ([pscustomobject] graphs) anyway, you can simply use Invoke-RestMethod rather than Invoke-WebRequest, because Invoke-RestMethod has ConvertFrom-Json built in, in a manner of speaking:

$path = "https://api.statuspage.io/v1/pages/$page_id/$endpoint"

# Retrieves JSON *and* parses it into objects.
$result = Invoke-RestMethod -Uri $path -Method GET

As for what you tried:

$req = Invoke-WebRequest ...

Invoke-WebRequest returns a single object, namely and instance of BasicHtmlWebResponseObject (PowerShell [Core] v6+) / HtmlWebResponseObject (Windows PowerShell), which is a wrapper object with metadata that stores the content of the response received in the .Content property.

In your case, .Content contains JSON as a single string, which ConvertFrom-Json can parse into a nested object(s).

To parse this JSON string into one or more (potentially nested) objects ([pscustomobject] graphs):

$result = ConvertFrom-Json $req.Content

Note that even $result = ConvertFrom-Json $req would work, because when a response object is implicitly stringified, it interpolates to the value of its .Content property.

As Theo points out in a comment, you can also use the pipeline:

$result = $req | ConvertFrom-Json
Sign up to request clarification or add additional context in comments.

Comments

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.