Quick Links
In many programming languages, there is the concept of scope.
Defined as what variables and functions are available in what context.
What are the PowerShell Scopes?
As mentioned in the introduction, there are several primary scopes.
When referencing scopes, you usually use scope prefixes to reach variables outside the current, local, scope.
This is easiest to understand through examples.
Upon launching PowerShell, all initial variables are globally scoped.
Local Scope
The current scope is always local, and therefore the default scope as well.
When you dot-source a script, such as.
my-script.ps1, you will add the entire output of that script to the local scope!
Script Scope
Finally, the script scope is a bit more complicated.
What is the Private, Using, Workflow, and AllScope options?
Along with the general scopes, there are several options that can modify the visibility or availability of variables.
So what are these different options with scopes?
This will only work withInvoke-Commandwhen it is being run on a remote computer such as with theComputerNameparameter.
Workflow and AllScope
Although much less used, there are two additional modifiers.
TheWorkflowmodifier is used to reference variables in a PowerShell Workflow (not available in PowerShell Core/7).
TheAllScopemodifier will make a variable available in all scopes.
Conclusion
Scopes are useful to limiting the visibility and availability of variables, functions, and aliases.
Scopes can also be troublesome when it is not clear what scope a variable is in.