Why does PowerShell flatten arrays automatically?

情到浓时终转凉″ 提交于 2020-01-14 10:39:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!