Powershell添加到多维数组

时间:2016-11-04 21:17:51

标签: powershell multidimensional-array

我想在powershell中创建一个多维数组,如下所示:

$array[0] = "colours"
$array[0][0] = "red"
$array[0][1] = "blue"
$array[1] = "animals"
$array[1][0] = "cat"
$array[1][0] = "dog"

这是我试过的:

$array = @()
$array += "colours"
$array += "animals"

$array[0] # outputs "colours"
$array[1] # outputs "animals"

$array[0] = @()
$array[1] = @()

$array[0] += "red"
$array[0] += "blue"
$array[1] += "cat"
$array[1] += "dog"

$array[0] # outputs "red", "blue" - i expected "colours" here
$array[0][0] # outputs "red"

我很欣赏任何提示。

提前致谢

2 个答案:

答案 0 :(得分:4)

无法执行您尝试使用嵌套数组

$array = @()
$array += "colours"

使$array[0]包含字符串colours, 但是,然后通过将空数组分配给$array[0]$array[0] = @()替换该值。这样,您的colours已消失

您稍后使用字符串redblue填充该数组,以便$array[0]最终包含一个2元素字符串数组@( 'red', 'blue' )

一种选择是使用哈希表 作为顶级数组元素的类型:

$array = @()
$array += @{ name = 'colours'; values = @() }

$array[0].values += 'red'
$array[0].values += 'blue'

$array[0].name   # -> 'colours'
$array[0].values # -> @( 'red', 'blue' )

答案 1 :(得分:3)

看起来您最好使用[hashtable](也称为关联数组):

$hash = @{
    colours = @('red','blue')
    animals = @('cat','dog')
}

$hash.Keys  # show all the keys

$hash['colours']  # show all the colours
$hash.colours   # same thing

$hash['colours'][0]  # red

$hash['foods'] = @('cheese','biscuits')  # new one
$hash.clothes = @('pants','shirts')  #another way

$hash.clothes += 'socks'