Why my array is reinitialized on each run?

This topic contains 2 replies, has 3 voices, and was last updated by Profile photo of Tim Pringle Tim Pringle 1 year, 9 months ago.

  • Author
    Posts
  • #23355
    Profile photo of GS
    GS
    Participant

    Probably totally stupid but can not figure out why $script scope Array variable is reinitialized on each run of the function

    $script:results = @()
    
    Function Remember()
    {
    $results+="dd"
    }
    Remember
    Remember
    Remember
    
  • #23356
    Profile photo of Jack Neff
    Jack Neff
    Participant

    Nope I see what you mean. My example code got buggered up by the forum but maybe I'll upload screenshot. Definitely some weirdness going on.

  • #23359
    Profile photo of Tim Pringle
    Tim Pringle
    Participant

    Hey GS,

    You need to refer to the scoped variable within the function, so you'd write it like this :

    $results = @()
    
    Function Remember()
    {
        $script:results += 'dd'
    }
    
    Remember
    Remember
    

    Would give

    PS 03/14/2015 09:52:23> $results
    dd
    dd
    

    It's down to yourself of course, but I normally only use a function to output the result directly, and leave the assignment to the calling code. Your function is locked to the use of a single variable, will not be suitable for parameter input, and in the long run your script will be harder to read. Another way to write the code would be:

    $results = @()
    
    Function Remember()
    {
        'dd'
    }
    
    $Results +=Remember
    $Results += Remember
    

You must be logged in to reply to this topic.