4

Json conversion with between result

> $container=az container list -o json|convertfrom-json
> $container|select name,provisioningstate

Output:

name           provisioningState
----           -----------------
master         Succeeded
pasbackground1 Succeeded
sftp           Succeeded

Json conversion without between result

> az container list -o json|convertfrom-json|select name,provisioningstate

Output:

 name provisioningstate
---- -----------------

I would expect the same result here as above.

why saving a temporary result brings different results than if the pipe commands are specified in a row.

1 Answers1

5

By default, the runtime engine unrolls (or enumerates) all collection types when feeding output to a dowstream cmdlet

However, ConvertFrom-Json in PowerShell versions up to v6.x returns its results in a way that prevents the runtime from enumerating them - so the next cmdlet in the pipeline receives an [object[]] array as a single pipeline item.

You can solve this in a number of ways:

  • Nest the initial pipeline:
(az container list -o json |ConvertFrom-Json) |Select Name,ProvisioningState
  • Let ForEach-Object unroll the array on return:
az container list -o json |ConvertFrom-Json |ForEach { $_ } |Select Name,ProvisioningState
  • Use an intermediate variable (as you've already found):
$containers = az container list -o json |ConvertFrom-Json 
$containers |Select Name,ProvisioningState
  • Upgrade to a newer version of PowerShell
    • The default behavior was changed in PowerShell [Core] 7.0
if($PSVersionTable['PSVersion'].Major -ge 7){
  az container list -o json |ConvertFrom-Json |Select Name,ProvisioningState
}
mklement0
  • 382,024
  • 64
  • 607
  • 775
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206