Why does PowerShell flatten arrays automatically?

前端 未结 3 1714
遇见更好的自我
遇见更好的自我 2021-01-18 13:32

I\'ve written some pwsh code

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


        
3条回答
  •  無奈伤痛
    2021-01-18 14:08

    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.

提交回复
热议问题