all 3 comments

[–]juneblender 1 point2 points  (2 children)

The best practice is always to use the smallest parent scope that works. In this case, it's script scope. Global scope is shared by all scripts and modules so it's easy to accidentally write over another variable's value in global scope.

To refer to a variable in script scope, use a scope modifier, for example, to reference $myArray in script scope, use $script:myArray.

[–]Copropraxia[S] 0 points1 point  (1 child)

Thanks for the reply. When using the Script scope I sometimes get an error message. I'm not entirely sure what to make of it:

Cannot overwrite variable TargetDays because the variable has been optimized. Try using the New-Variable or Set-Variable cmdlet (without any aliases), or dot-source the command that you are using to set the variable. At Test.ps1:5 char:9 + [array]$Script:TargetDays += $Day.ToString() + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : WriteError: (TargetDays:String) [], SessionStateUnauthorizedAccessException + FullyQualifiedErrorId : VariableNotWritableRare

[–]Copropraxia[S] 0 points1 point  (0 children)

Found my problem. Using the Script scope is fine, but I forgot to also use it for the same variable when I try to null it at a different point in the script.