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?

/wordpress/wp-content/uploads/csit/2020/12/0b02ecf4.png

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.

/wordpress/wp-content/uploads/csit/2020/12/f7b2df16.png

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.

/wordpress/wp-content/uploads/csit/2020/12/cb9fd08c.png

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?

/wordpress/wp-content/uploads/csit/2020/12/37a19f67.png

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.