I've seen this syntax on a variable b开发者_开发问答efore and not quite sure exactly what it is:
$script:Foo = "Bar"
The syntax $script:Foo
is most commonly used to modify a script-level variable, in this case $Foo
. When used to read the variable, usually $Foo
is sufficient. For example rather than write this:
verbose-script.ps1
$script:foo = ''
function f { $script:foo }
I would write this (less verbose and functionally equivalent):
script.ps1
$foo = ''
function f { $foo }
Where $script:Foo
is crucial is when you want to modify a script-level variable from within another scope such as a function or an anonymous scriptblock e.g.:
PS> $f = 'hi'
PS> & { $f; $f = 'bye';$f }
hi
bye
PS> $f
hi
Notice that $f
outside the scriptblock did not change even though we modified it to bye
within the scriptblock. What happened is that we only modified a local copy of $f
. When you don't apply a modifier like script:
(or global:
), PowerShell will perform a copy-on-write
on the higer-scoped variable into a local variable with the same name.
Given the example above, if we really wanted to make a permanent change to $f
, we would then use a modifier like script:
or global:
e.g.:
PS> $f = 'hi'
PS> & { $f; $global:f = 'bye';$f }
hi
bye
PS> $f
bye
The script:
prefix causes the name on the right hand side to be looked up in the script scope. Essentially data which is local to the script itself. Other valid scopes include global, local and private.
The help section for scope contains a bit of detail on this subject.
help about_Scopes
精彩评论