Why my array is reinitialized on each run?

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

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.

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