简体   繁体   English

合并 2 个 PowerShell 数组

[英]Combine 2 PowerShell arrays

I'm trying to figure out how to combine 2 arrays as explained here by Microsoft.我试图弄清楚如何组合 2 个数组,如 Microsoft 在此处解释的那样。

$Source = 'S:\Test\Out_Test\Departments'
$Array = Get-ChildItem $Source -Recurse

$Array.FullName | Measure-Object # 85
$Array.FullName + $Source | Measure-Object # 86
$Source + $Array.FullName | Measure-Object # 1

The following only has 1 item to iterate through:以下只有 1 项要迭代:

$i = 0
foreach ($t in ($Source + $Array.FullName)) {
    $i++
    "Count is $i"
    $t
}

My problem is that if $Source or $Array is empty, it doesn't generate seperate objects anymore and sticks it all together as seen in the previous example.我的问题是,如果$Source$Array为空,它不会再生成单独的对象,而是将它们粘在一起,如前面的示例所示。 Is there a way to force it into separate objects and not into one concatenated one?有没有办法强制它进入单独的对象而不是一个连接的对象?

In PowerShell, the left-hand side operand determines the operator overload used, and the right-hand side gets converted to a type that satisfies the operation.在 PowerShell 中,左侧的操作数确定使用的运算符重载,而右侧的操作数被转换为满足操作的类型。

That's why you can observe that这就是为什么你可以观察到

[string] + [array of strings] results in a [string] (Count = 1) [string] + [array of strings]结果为[string] (Count = 1)
[array of strings] + [string] results in an [array of strings] (Count = array size + 1) [array of strings] + [string]结果为[array of strings] (计数 = 数组大小 + 1)

You can force the + operator to perform array concatenation by using the array subexpression operator ( @() ) on the left-hand side argument:您可以通过在左侧参数上使用数组子表达式运算符( @() ) 来强制+运算符执行数组连接:

$NewArray = @($Source) + $Array.FullName

This is because $Source is a System.String and + is probably an overloaded for Concat .这是因为 $Source 是System.String并且+可能是Concat的重载。 If you cast $Source to an array, you will get your desired output:如果您将$Source转换为数组,您将获得所需的输出:

[array]$Source + $Array.FullName | Measure-Object # 86

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM