问题
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
回答1:
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.
,
effectively 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.
回答2:
With foreach-object, it's usually useful to unwrap the array:
ps | foreach modules | sort -u modulename
来源:https://stackoverflow.com/questions/57023626/why-does-powershell-flatten-arrays-automatically