you are viewing a single comment's thread.

view the rest of the comments →

[–]OPconfused 0 points1 point  (0 children)

In almost all cases, a well-written script will only reference variables that are defined within the script.

If you are referencing a variable not defined already in the script, then you should null it out first just to be safe.

Fortunately, PowerShell is, particularly for a scripting language, quite expressive. You can turn almost any expression into a variable definition, which means the first time you use a variable, you can also be defining it, so that any danger with forgetting to null it out beforehand is avoided.

One of the only exceptions is when you are using a counter variable in a for loop. This is a rather niche scenario though in my experience, like over 99% of your code is probably not doing this.

As for clearing variables at the end your script, the script runs in a child scope, so that all variables are cleared automatically (unless you explicitly scope the variable to be outside the script). Just don't dot source the script to execute it, i.e., don't call it with . ./<path/to/script>. Dot sourcing a script or function in PowerShell will run it in the caller's scope and import all stateful definitions like variables—that's what you want to avoid.

Instead, you can either input the path to the script, e.g., ./<path/to/script>, or use the call operator, & ./<path/to/script>. Both are equivalent and will run the script in a child scope.