[英]Powershell: is there a Scope Preference for Variables?
Morning guys, hopefully just a quick one.早上好,希望只是一个快速的。 Is there a Scope Preference for Variables like there is for some other settings ( $ErrorActionPreference
, etc)?变量是否有 Scope 首选项,就像其他一些设置( $ErrorActionPreference
等)一样? I'm working on a script that has a bunch of functions that call on information created in each other and I'm just looking to avoid writing $Script:
or $Global:
in front of each variable everytime (I'm being lazy I know)我正在编写一个脚本,它有一堆函数调用彼此创建的信息,我只是想避免每次都在每个变量前面写$Script:
或$Global:
(我很懒我知道)
Is there a Scope Preference for Variables like there is for some other settings (
$ErrorActionPreference
, etc)?变量是否有 Scope 首选项,就像其他一些设置($ErrorActionPreference
等)一样?
No, scoping behavior is part of the language's core runtime semantics and is not configurable.不,作用域行为是语言核心运行时语义的一部分,不可配置。
I'm working on a script that has a bunch of functions that call on information created in each other and I'm just looking to avoid writing
$Script:
or$Global:
in front of each variable everytime我正在编写一个脚本,它有一堆函数调用彼此创建的信息,我只是想避免每次都在每个变量前面写$Script:
或$Global:
You don't need it everytime - you only need the scope modifier when you're writing to a parent scope.您不需要每次都需要它 - 当您写入父 scope 时,您只需要 scope 修饰符。
Resolution of variables for reading will fall back through parent scopes and eventually the global scope, until a matching variable is found:用于读取的变量的解析将通过父作用域并最终返回全局 scope,直到找到匹配的变量:
# variable defined at script scope, functions defined in here will fall back to resolving this when `$Config` is referenced
$Config = @{
'setting' = 'initialValue'
}
function Update-Config {
# Scope modifier is only necessary when "writing up" through the scope stack
$script:Config = @{
setting = 'updatedValue'
}
}
function Do-Stuff {
$setting = $Config['setting'] # no need to use script: here
Write-Host "About to do something with '$setting'"
}
Do-Stuff
Update-Config
Do-Stuff
Executing the above in a script file will print:在脚本文件中执行上述操作将打印:
About to do something with 'initialValue'
About to do something with 'updatedValue'
Note that for functions bound to a module, the script:
scope is shared across the module - writing to $script:Variable
in one module function will cause resolution of non-local $Variable
to resolve correctly in any other function in the same module请注意,对于绑定到模块的函数, script:
scope 在模块之间共享 - 写入一个模块中的$script:Variable
function 将导致非本地$Variable
的解析在任何其他模块中正确解析
For more information about scoped variable resolution, consult the about_Scopes
help file有关范围变量解析的更多信息,请参阅about_Scopes
帮助文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.