Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Return value of Invoke-RestMethod or ConvertFrom-Json looks like a list but it's not a list

Context:

Return value of Invoke-RestMethod looks like a list of objects:

> $headers = @{ Accept = "application/json"; Authorization = "Bearer 0123456789abcdef0123456789abcdef01234567"; }
> Invoke-RestMethod -Headers $headers -Method Get -Uri https://api.github.com/repos/PowerShell/PowerShell/git/refs/heads

ref                                 url
---                                 ---
refs/heads/master                   https://api.github.com/repos/PowerShell/PowerShell/git/refs/...
refs/heads/rjmholtdsl-csharp-protpt https://api.github.com/repos/PowerShell/PowerShell/git/refs/...
refs/heads/source-depot             https://api.github.com/repos/PowerShell/PowerShell/git/refs/...

Problem:

You wrote one-liner to filter the return value of Invoke-RestMethod, but the result is same as above.

> Invoke-RestMethod -Headers $headers -Method Get -Uri https://api.github.com/repos/PowerShell/PowerShell/git/refs/heads |
      Where-Object { $_.ref -like "*source*" }

ref                                 url
---                                 ---
refs/heads/master                   https://api.github.com/repos/PowerShell/PowerShell/git/refs/...
refs/heads/rjmholtdsl-csharp-protpt https://api.github.com/repos/PowerShell/PowerShell/git/refs/...
refs/heads/source-depot             https://api.github.com/repos/PowerShell/PowerShell/git/refs/...

Reason:

The return value of Invoke-RestMethod and ConvertFrom-Json looks like a list, but actually, it’s a not a list but single object.

> Invoke-RestMethod -Headers $headers -Method Get -Uri https://api.github.com/repos/PowerShell/PowerShell/git/refs/heads | Measure-Object

Count    : 1
 ...

Solution:

Pass the return value through ForEach-Object and output each item in the return value.

> Invoke-RestMethod -Headers $headers -Method Get -Uri https://api.github.com/repos/PowerShell/PowerShell/git/refs/heads |
      ForEach-Object { $_ } | Where-Object { $_.ref -like "*source*" }