将数组附加到 PowerShell 中的数组数组 [英] Append an Array to an Array of Arrays in PowerShell

查看:57
本文介绍了将数组附加到 PowerShell 中的数组数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用位于磁盘上的 CSV 文件以编程方式在 PowerShell 中构建多维数组.我一直在将数组导入一个临时变量,然后将数组附加到数组中.我得到一个包含总行数的数组,而不是数组数组.我用较小的数组解决了这个问题,发现了以下内容:

I'm trying to build up a multi-dimensional array in PowerShell programmatically using CSV files located on disk. I have been importing the array into a temporary variable and then appending the array to the array. Instead of an array of arrays I get a single array with the total number of rows. I worked it out with smaller arrays and found the following:

$array1 = "11","12","13"
$array2 = "21","22","23"
$array3 = "31","32","33"

$arrayAll = $array1, $array2, $array3
$arrayAll.Count # returns 3

$arrayAll = @();
$arrayAll += $array1
$arrayAll += $array2
$arrayAll += $array3

$arrayAll.count # returns 9

构建数组的第一种方法有效,但我需要能够使用第二种方法.我该如何解决这个问题?

The first method for building the array works but I need to be able to use the second method. How do I fix this?

推荐答案

这是一个常见的问题,数组(和其他集合)可能会意外地"展开.使用逗号运算符(它使/强制使用单个项目的数组并避免展开):

It's a common gotcha, arrays (and other collections) may get unrolled "unexpectedly". Use the comma operator (it makes/enforces an array with a single item and avoids unrolling):

$array1 = "11","12","13"
$array2 = "21","22","23"
$array3 = "31","32","33"

$arrayAll = $array1, $array2, $array3
$arrayAll.Count # returns 3

$arrayAll = @()
$arrayAll += , $array1
$arrayAll += , $array2
$arrayAll += , $array3

$arrayAll.count # returns 3

$arrayAll[1] # gets "21","22","23", i.e. $array2

这篇关于将数组附加到 PowerShell 中的数组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆