Arrays that do not behave in a script

I am trying to create a very simple array of values. From a PS C:> everything works as expected. But as soon as I use a script, the arrays start to misbehave. Instead of creating new array of elements, I am just getting a single concatenated string. What as I doing wrong?

cls

$a = “loader1x”
$a
$a += “loader2x”
$a
$a += “loader3x”
$a
$a += “loader4x”
$a
$a.length
$a[1]
$a[3]
foreach($b in $a)
{
$b
$b.length

}

Output:

loader1x
loader1xloader2x
loader1xloader2xloader3x
loader1xloader2xloader3xloader4x
32
o
d
loader1xloader2xloader3xloader4x
32

The += operator behavior depends on what’s on the left side. Your $a variable is originally declared as a string, not an array, so you get string concat behavior. Declaring it as an array will change that behavior:

$a = @()

$a += 'A string'
$a += 'Another string'
# etc

You will need to tell the PowerShell engine that you want an array object with @() for example otherwise $a = “loader1x” will just be a string object.

Try below:

cls

$a = @("loader1x")
$a
$a += "loader2x"
$a
$a += "loader3x"
$a
$a += "loader4x"
$a
$a.length
$a[1]
$a[3]
foreach($b in $a)
{
    $b
    $b.length
}

Thanks Guys,
Dave, your solution doesn’t seem to work for me. However, Daniel’s does. I can get back to work now!