【问题标题】:Why is my PowerShell multi dimensional array being interpreted as a 1 dimensional array?为什么我的 PowerShell 多维数组被解释为一维数组?
【发布时间】:2011-02-22 11:27:02
【问题描述】:

我有以下代码:

function HideTemplates($File, $Templates)
{
  foreach ($Template in $Templates)
  {
    Write-Host $Template[0] $Template[1] $Template[2]
  }
}

HideTemplates "test.xml" @(("one", "two", "three"))
HideTemplates "test.xml" @(("four", "five", "six"), ("seven", "eight", "nine"))

打印出来:

o n e
t w o
t h r
four five six
seven eight nine

我希望它打印出来:

one two three
four five six
seven eight nine

我的代码做错了吗?有没有办法强制 PowerShell 以不同的方式处理具有单个项目的多维数组?

【问题讨论】:

    标签: arrays powershell multidimensional-array


    【解决方案1】:

    像这样调用你的函数:

    HideTemplates "test.xml" (,("one", "two", "three"))
    HideTemplates "test.xml" (,("four", "five", "six"),("seven", "eight", "nine"))
    

    如果内容已经是一个数组,则数组子表达式即@() 什么也不做。改用逗号运算符,它将始终创建一个数组,其中一个元素围绕它后面的任何元素。请注意,您必须添加一组额外的括号,否则:

    HideTemplates "test.xml",("one", "two", "three")
    

    将被视为数组类型的单个参数,而不是两个参数。

    【讨论】:

    • 谢谢——效果很好。我曾尝试在末尾添加一个额外的逗号——(("one","two"),)——但这没有用。
    猜你喜欢
    • 2016-03-25
    • 1970-01-01
    • 2014-11-25
    • 2019-06-13
    • 2019-01-15
    • 1970-01-01
    • 2023-03-26
    • 2019-06-29
    相关资源
    最近更新 更多