0

I have a loop over data that call a local function.

In this function, I feed an global scoped array.

However, at the end, the array is empty. Why ? and how to fix ?

To reproduce the behavior, try this :

$myArray = @() # Global array

function Invoke-SomeAction{
    param(
        [Parameter()]
        [int]$Val
    )

    $myArray += $Val
}

1..10 | % {

    Invoke-SomeAction -Val $_

}

$myArray.Count # Expect 10, got 0

If I remove the function call like this:

$myArray = @() # Global array

1..10 | % {

    $myArray += $_

}

$myArray.Count # Expect 10, got 10

It behaves as expected.

PS: if it matters, here's my $PSVersionTable:

Name                           Value                                                                                                                           
----                           -----                                                                                                                           
PSVersion                      5.1.14393.3053                                                                                                                  
PSEdition                      Desktop                                                                                                                         
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                         
BuildVersion                   10.0.14393.3053                                                                                                                 
CLRVersion                     4.0.30319.42000                                                                                                                 
WSManStackVersion              3.0                                                                                                                             
PSRemotingProtocolVersion      2.3                                                                                                                             
SerializationVersion           1.1.0.1            
0

1 Answer 1

1

The reason is scopes are different. You are trying to add to $myArray in function scope, yet you need to add in script scope. Try this:

$myArray = @() # Global array

function Invoke-SomeAction{
    param(
        [Parameter()]
        [int]$Val
    )
#this sets a variable scope to script 
    $script:myArray += $Val
}

1..10 | % {

    Invoke-SomeAction -Val $_

}

$myArray.Count

More on this here: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.1

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.