Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does PowerShell flatten arrays automatically?

I've written some pwsh code

"a:b;c:d;e:f".Split(";") | ForEach-Object { $_.Split(":") }
# => @(a, b, c, d, e, f)

but I want this

// in javascript
"a:b;c:d;e:f".split(";").map(str => str.split(":"))
[ [ 'a', 'b' ], [ 'c', 'd' ], [ 'e', 'f' ] ]

a nested array

@(
    @(a, b),
    @(c, d),
    @(e, f),
)

Why? and what should I do

like image 212
Kk Shinkai Avatar asked Jul 14 '19 00:07

Kk Shinkai


1 Answers

Use the unary form of ,, PowerShell's array-construction operator:

"a:b;c:d;e:f".Split(";") | ForEach-Object { , $_.Split(":") }

That way, the array returned by $_.Split(":") is effectively output as-is, as an array, instead of having its elements output one by one, which happens by default in a PowerShell pipeline.

, creates a - transient - wrapper array whose only element is the array you want to output. PowerShell then unwraps the wrapper array on output, passing the wrapped array through.

like image 107
mklement0 Avatar answered Oct 17 '22 21:10

mklement0