Currently, the default variable scope allows variables to be accessed in child scopes.
I always had a lot of problems with this in bigger scripts.
It would be nice to have an option, e.g. at the beginning of a script, which tells PS
that the default scope should be private for this script.
That is the purpose of declaring your variables with scope, .e.g, $private:myVar
Correct. I believe the request is to have a way in the script to set such a scope to be the _default_ for all variables in that scope, so that when creating an unscoped variable it is automatically assigned the private scope.
Yes, exactly. When you have very long scripts, it's very ugly to prefix all variables with private
PowerShell's dynamic scoping is a problem in other areas too, notably with not wanting Set-StrictMode settings to apply to child scopes ((third-party) code is often written with the assumption that no strict mode is in effect, and one going into effect in the caller's scope can break the code - see the (languishing) lexical strict-mode RFC at https://github.com/PowerShell/PowerShell-RFC/issues/7
For more robust code, lexically scoped variables, or their emulation with the $private: scope modifier, but _without the latter's ceremony_ would indeed be helpful, but requires an _opt-in_ mechanism so as not to break backward compatibility.
Conceivably, a new using statement could using be introduced that makes all local variables private _by default_, along the lines of using private variables; however, this implies that the option is only available at the _file_ level, not to individual functions. [_update_: also, the effect would have to be lexically scoped, which the current using statements are _not_].
Not a bad suggestion, @mklement0. For myself, I was imagining introducing a preference variable; e.g., $PSDefaultVariableScope = 'Private'
The problem with preference variables is again their dynamic scoping - child scopes that weren't written with all-private variables in mind could break.
I suggested using under the mistaken assumption was that they are lexically scoped to the enclosing script / script module, but as it turns out they're _not_, not even in the using namespace case.
I suppose something like $private:PSDefaultVariableScope = 'Private' would work in a given scope, come to think of it, but that is obscure.
This isn't answered yet
This issue has been marked as answered and has not had any activity for 1 day. It has been closed for housekeeping purposes.
Most helpful comment
Correct. I believe the request is to have a way in the script to set such a scope to be the _default_ for all variables in that scope, so that when creating an unscoped variable it is automatically assigned the
privatescope.