Arrays that do not behave in a script

This topic contains 3 replies, has 3 voices, and was last updated by  Mark Brown 2 years ago.

  • Author
    Posts
  • #30476

    Mark Brown
    Participant

    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

  • #30480

    Dave Wyatt
    Moderator

    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
    
  • #30481

    Daniel Krebs
    Moderator

    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
    }
    
  • #30490

    Mark Brown
    Participant

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

You must be logged in to reply to this topic.