I'm having problems adding an element to an array outside a function from within a function

I want to use a function to add an element to an array that was declared outside the function by calling the function. I’ve tried several approaches, however none effects the wanted effects, as shown below:

[EDIT: Image substituted by a text written as formatted code, with the directory credentials redacted]

PS C:\Users\REDACTED> $Q = @(); function QQ(){$Q += @(1)}; QQ; $Q;
PS C:\Users\REDACTED> $Q = @(); function QQ(){$Global:Q += @(1)}; QQ; $Q;
1
PS C:\Users\REDACTED> $Q = @(); function QQ(){$Global:Q += @(2)}; QQ; $Q;
2
PS C:\Users\REDACTED> $Q = @(); function QQ(){$Script:Q += @(2)}; QQ; $Q;
2
PS C:\Users\REDACTED> $Q = @(); function QQ(){$Script:Q += @(1)}; QQ; $Q;
1

Why are these results in the image happening and what can I do for having the effects I want? EDIT: Is there such a thing in PowerShell that an array doesn’t accept having equal values?

Please do not post images of code or console output. Instead post the plain text and format it as code.

To you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

1 Like

You keep calling $Q = @() so you keep setting it to an empty array

PS C:\Users\REDACTED> $Q = @(); function QQ(){$Q += @(1)}; QQ; $Q;
PS C:\Users\REDACTED> function QQ(){$Global:Q += @(1)}; QQ; $Q;
1
PS C:\Users\REDACTED> function QQ(){$Global:Q += @(2)}; QQ; $Q;
1
2
PS C:\Users\REDACTED> function QQ(){$Script:Q += @(2)}; QQ; $Q;
1
2
2

Thanks. Well, it didn’t work with $Q += @(1) however it worked with Global and Script. Why didn’t it work with $Q += @(1)?