Foreach subvalue of array?


Im trying to automate some processes through an API, and cant seem to find a way around this issue.

So im pulling all records from the API to $Records, that is defined as an array:

$Records = Invoke-WebRequest -Uri "https://server.domain.tld/v2/link/to/api" -ContentType "application/json" -Method GET


My issue is that the $Records variable is an Array, but the Content section of the array, is defined as an string.

StatusCode : 200
StatusDescription : OK
Content : {
"records": [
"record_number": 3291,
"name": "@",
"ttl": 600,
"data": "ns1.domain.tld",
"type": "NS",
RawContent : HTTP/1.1 200 OK
Server: nginx
Date: Wed, 10 Feb 2021 20:42:28 GMT
Transfer-Encoding: chunked
Connection: keep-alive
X-Robots-Tag: noindex, noarchive, nosnippet
Content-Type: application/json; ch…
Headers : {[Server, System.String[]], [Date, System.String[]], [Transfer-Encoding, System.String[]], [Connection, System.String[]]…}
Images : {}
InputFields : {}
Links : {}
RawContentLength : 4217
RelationLink : {}


I wanted to loop through each of the Content values in $Records.Content, but i cant seem to find a way to do this, since the Content section, is an string - or am i wrong?



Have you tried Invoke-RestMethod instead of Invoke-WebRequest ?

I keep getting errors when trying to reply. Here is what I have been trying to post:

Have you tried Invoke-RestMethod instead of Invoke-WebRequest?

Without getting into the API, if you have a string you want to split into an array so you can do things like iterate over, look at the -split operator. It will turn a string into an array of strings based on a regular expression (delimiter to split on) or any white space (when used as unary operator). See get-help about_split.

As Fer was saying, Invoke-RestMethod will convert the JSON into a PSObject, which can be parsed. It appears Content-Type is a semi-colon delimited string, so as Mike said you can use split to turn that into an array.

$results = Invoke-RestMethod ...

$arrContentType = $results.'Content-Type' -split ':'


I feel stupid for having asked this question, since ive used Invoke-RestMethod several times now.

Thanks alot for the answers. I decided to go with Invoke-Restmethod, and then foreach ($Record in $Records.records)