In step 1 you define a local variable called $PI
with the value 3.14
.
In steps 2 and 3 you create a new .ps1
file and then put code in that script file to assign the value 3.14
to $PI
and then displays the value of $PI
. Since the file defines a new variable, with the same name, and then displays it the output will show the value of the variable as defined by the script.
In step 4 you run the script.
Finally in step 5 you show that the value of $PI
is still 3.14
.
This behavior is defined in PowerShell under the Scopes documentation. Here's the high level important points made in the docs.
- When you start a PS session then a new scope is created
- When you run a script file then it creates a new child scope for that file
- By default a child scope has access to the parent scope
- Child scopes can run script files that create their own child scopes
- When you reference a variable it'll start in the current scope and walk its way back to the parent scope if it isn't found at which point it'll create it
Here's the general summary based upon the code you wrote.
- You declare a variable called
$PI
in the parent scope - You run a file script
- The file gets a new child scope
- The script has access to
$PI
from the parent scope - The script creates its own
$PI
variable in the child scope and changes the value - Whenever the script references
$PI
it is now using its child scope version of that - When the script file ends then the child scope's
$PI
variable goes away
- The parent scope's
$PI
is now accessible again
You can sort of see this behavior by printing out the $PI
variable in the file BEFORE you change the value.