Nicolas Leucci
Nicolas Leucci

Reputation: 3339

Difference between two ways of creating arrays

I just encountered a problem about an array in Powershell and I just want to understand what was happening.

Why is this way :

$Path = 'C:\'
$File1 = $Path + 'File1.txt'
$File2 = $Path + 'File2.txt'
$Files= @($File1, $File2)

Different from this way :

$Path = 'C:\'
$Files= @($Path + 'File1.txt', $Path + 'File2.txt')

Because with the first one, I can parse it like this :

$Files| ForEach-Object {
    $Test = Get-Item -Path $_
}

But I can't with the second one, unless I created it like this :

$Path = 'C:\'
$Files = @(($Path + 'File1.txt'), ($Path + 'File2.txt'))

Is there another clean way to create an array ? Thank you !

Upvotes: 2

Views: 43

Answers (1)

G42
G42

Reputation: 10019

In the first instance, you are creating an array with 2 elements. In the second instance, you are creating an array with a single element. PowerShell is not processing $Path + 'File1.txt' as one.

You can check the number of elements in an array by using $Files.Count: it will show 2 for the first method, and 1 for the second.

You can get around this by using brackets () as you have identified, or using {} to wrap the variable:

$Files= @("${Path}File1.txt", "${Path}File2.txt")

If your plan is to use this in a ForEach-Object, you could just use $Path in that loop:

$Path = 'C:\'
$Files= @('File1.txt', 'File2.txt')

$Files| ForEach-Object {
    $Test = Get-Item -Path "${Path}$_"
}

Addendum

As per Bacon Bits' helpful comment, this is due to Operator Precedence, with , having a higher precedence than +

@($Path + 'File1.txt', $Path + 'File2.txt')

becomes:

($Path) + ('File1.txt', $Path) + ('File2.txt')

instead of:

($Path + 'File1.txt'), ($Path + 'File2.txt')

Upvotes: 3

Related Questions