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

查看:254
本文介绍了在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天全站免登陆