Reputation: 421
I have trouble understanding the difference between the script:
scope and the global:
scope, when using them in a script.
Can someone give me an example, in which a global-scoped variable retains it's value and the scipt-scoped variable does not?
Upvotes: 1
Views: 196
Reputation: 200573
When in doubt, read the documentation:
Global:
The scope that is in effect when Windows PowerShell starts. Variables and functions that are present when Windows PowerShell starts have been created in the global scope. This includes automatic variables and preference variables. This also includes the variables, aliases, and functions that are in your Windows PowerShell profiles.
[...]
Script:
The scope that is created while a script file runs. Only the commands in the script run in the script scope. To the commands in a script, the script scope is the local scope.
Example:
PS C:\> $foo = 'a' PS C:\> Get-Content .\test.ps1 "global 1: $global:foo" "script 1: $script:foo" $foo = 'b' # <- this modifies $foo in the script scope "global 2: $global:foo" "script 2: $script:foo" $global:foo = 'c' # <- this modifies $foo in the global scope "global 3: $global:foo" "script 3: $script:foo" PS C:\> .\test.ps1 global 1: a script 1: global 2: a script 2: b global 3: c script 3: b PS C:\> $foo c
Upvotes: 2