6

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?

2
  • 2
    @($Source;$Array.FullName) Commented Feb 15, 2016 at 9:14
  • Yes yes yes!! That's it! Thank you very much PetSerAl, you helped me a lot here! Commented Feb 15, 2016 at 9:16

3 Answers 3

15

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Mathias, now I finally understand why this different behavior is happening. For ease of reading I'll use the following @($Source;$Array.FullName) as suggested in the comments by PetSerAl.
@DarkLite1 Whatever floats your boat, glad I was able to teach you something new :)
2

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

1 Comment

+ is not an alias, it's simply overloaded (operators can be overloaded just like methods)
0
  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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.