【问题标题】:Looping through each row of 2D array with ForEach-Object使用 ForEach-Object 循环遍历二维数组的每一行
【发布时间】:2014-09-12 06:40:55
【问题描述】:

我尝试输入如下内容:

$test = ("c2","d8","e9"),(4,1,9)
(0..2) | % { "$test[0][$_] $test[1][$_]" }

我应该期望它输出:

c2 4
d8 1
e9 9

但我得到了这个:

System.Object[] System.Object[][0][0] System.Object[] System.Object[][1][0]
System.Object[] System.Object[][0][1] System.Object[] System.Object[][1][1]
System.Object[] System.Object[][0][2] System.Object[] System.Object[][1][2]

获得所需输出的正确方法是什么?

【问题讨论】:

    标签: powershell foreach rows multidimensional-array


    【解决方案1】:

    您需要将它们放在子表达式中。原因是当它在双引号内外推变量时,它从美元符号开始,并在有效变量名称的末尾停止外推。 [0] 不是变量名的一部分,因此将其包装在 $() 中,它可以正常工作:

    $test = ("c2","d8","e9"),(4,1,9)
    (0..2) | % { "$($test[0][$_]) $($test[1][$_])" }
    

    【讨论】:

      【解决方案2】:

      你可以直接在字符串中使用变量,但是当你需要扩展一些更复杂的东西,比如属性、数组中的项或其他表达式时,你需要使用子表达式$()

      $test = ("c2","d8","e9"),(4,1,9)
      (0..2) | % { "$($test[0][$_]) $($test[1][$_])" }
      c2 4
      d8 1
      e9 9
      

      【讨论】:

        【解决方案3】:

        或者你可以使用字符串连接:

        $test = ("c2","d8","e9"),(4,1,9)
        (0..2) | % {$test[0][$_] + " " + $test[1][$_]}
        

        输出:

        c2 4
        d8 1
        e9 9
        

        【讨论】:

        • +1 这样一个老派的解决方案 :) 喜欢在 powershell 中扩展变量和子表达式。一个很棒的功能。
        猜你喜欢
        • 1970-01-01
        • 2014-12-22
        • 2016-04-06
        • 2013-03-26
        • 2018-11-02
        • 2016-01-20
        • 1970-01-01
        • 2010-10-24
        相关资源
        最近更新 更多