DarkLite1
DarkLite1

Reputation: 14705

Combine 2 PowerShell arrays

I'm trying to figure out how to combine 2 arrays as explained here by 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:

$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. Is there a way to force it into separate objects and not into one concatenated one?

Upvotes: 6

Views: 6387

Answers (3)

Luke
Luke

Reputation: 2300

  1. Place your elements inside parentheses preceded by a dollar sign.
  2. Separate your elements with semicolons.

Applied to the case of the initial question:

$($Source; $Array.FullName) | Measure-Object #86

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 58931

This is because $Source is a System.String and + is probably an overloaded for Concat. If you cast $Source to an array, you will get your desired output:

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

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

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.

That's why you can observe that

[string] + [array of strings] results in a [string] (Count = 1)
[array of strings] + [string] results in an [array of strings] (Count = array size + 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

Upvotes: 15

Related Questions