Search code examples
variablespowershellscoping

Have many functions add to same array variable


I have some pseudo code similar to the below

$funcValues = @(New-Object -TypeName psobject -Property @{'Function' = ''; 'Value' = '';}) 

function func1(){
    while($i -lt 5){
        $funcValues += @(New-Object -TypeName psobject -Property @{'Function' = 'func1'; 'Value' = $i;}) 
        $i++
    }
}

function func2(){
    while($i -lt 3){
        $funcValues += @(New-Object -TypeName psobject -Property @{'Function' = 'func2'; 'Value' = $i;}) 
        $i++
    }
}

func1
func2

$funcValues | Export-CSV C:\path\results.csv -noType

The goal is to have both functions add to the array and after calling the functions export the array to a csv. However when this code is inside a function, it doesn't write anything to the array, but if the code is outside a function, it works.

I'm guessing this has to do with variable scoping, but I'm very unfamiliar with how scoping works in powershell.


Solution

  • Your guess is correct. Try:

    function func1(){
        while($i -lt 5){
            $script:funcValues += @(New-Object -TypeName psobject -Property @{'Function' = 'func1'; 'Value' = $i;}) 
            $i++
        }
    }
    

    Note that you are creating an array of arrays. If that's not what you wanted, then use:

    $script:funcValues += New-Object -TypeName psobject -Property @{'Function' = 'func1'; 'Value' = $i;}
    

    And if you are using V3, you can simplify some more:

    $script:funcValues += [pscustomobject]@{'Function' = 'func1'; 'Value' = $i;}
    

    One last comment on the code - using += on an array isn't very fast. Arrays can't be resized, so += will create a new array, copying the elements from the original array and adding the elements at the end. If the array is small, then the syntax is clear and convenient, but if the arrays get large and performance matters, you might consider using a different data structure like ArrayList.