2

My question is - why is the output generated by a) statement different to that by b) statement?

$json = '[{"name": "george",
   "psw64": "AMnd8BFdd8BFd"
  },
 {"name": "lucy",
   "psw64": "AQ8BFdERjHoAw"
  }
]
'

# a) -- different output to b) --
convertfrom-json $json | foreach-object {
    $_.name + ': '+ $_.psw64
 }

# b) -- different output to a) --
$data = convertfrom-json $json
$data | foreach-object {
    $_.name + ': '+ $_.psw64
}

-- a) outputs --

george
lucy
:
AMnd8BFdd8BFd
AQ8BFdERjHoAw

-- b) outputs --

george: AMnd8BFdd8BFd
lucy: AQ8BFdERjHoAw

I simply don't understand why is there difference between passing the data directly from convertfrom-json and through a temporary variable.

My $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.22000.832
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.22000.832
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
Babla
  • 53
  • 5
  • 2
    `ConvertFrom-Json` deliberately prevents the "unrolling" of any top-level array when it sends its output. Use `... | Write-Output | ...` in between if you want to avoid the variable – Mathias R. Jessen Aug 16 '22 at 12:33
  • 2
    Before PowerShell (Core) 7.0, `ConvertFrom-Json` and `Invoke-RestMethod` unexpectedly sent arrays as _a whole_ through the pipeline, rather than element by element. The simplest workaround is to enclose the call in `(...)`, which forces enumeration. See the linked duplicate for details. – mklement0 Aug 16 '22 at 13:02

0 Answers0