PowerShell Series-Variables | Scope

PowerShell Series-Variables | Scope

Can be either local or global, By default limited to the Scope in which they're created, i.e., only available in the current function or script, in which they're created.

It's important to note that variable scope in PowerShell can vary based on how and where the code is executed (interactive session, script, function, etc.)

🪶 Variables created in the console, have a global scope.

🪶 Variables created within a script or a block, have local scope.

Examples: In the below example, I created a variable name called $Console_Variable, and if I want to use it it will be available in the entire console and it will show its availability as below. It means it is in Global scope.

Similarly, script variables are local to script itself as below

But not available in global scope. ($Script_Variable is not populating)

When we are trying to print $Script_Variables outside script then it wont get printed.

If we want to display $Script_Variable, then we use Scope modifier called "Global" as below