早上好,希望只是一個快速的。變數的范圍偏好是否像其他一些設定($ErrorActionPreference等)一樣?我正在撰寫一個腳本,它有一堆函式呼叫彼此創建的資訊,我只是想避免每次都寫$Script:或$Global:在每個變數前面(我知道我很懶)
uj5u.com熱心網友回復:
變數的范圍偏好是否像其他一些設定(
$ErrorActionPreference等)一樣?
不,作用域行為是語言核心運行時語意的一部分,不可配置。
我正在撰寫一個腳本,它有一堆函式呼叫彼此創建的資訊,我只是想避免每次都寫
$Script:或$Global:在每個變數前面
您不需要每次都需要它- 您只需要在寫入父范圍時使用范圍修飾符。
用于讀取的變數的決議將通過父作用域并最終回傳全域作用域,直到找到匹配的變數:
# 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
在腳本檔案中執行上述操作將列印:
About to do something with 'initialValue'
About to do something with 'updatedValue'
請注意,對于系結到模塊的函式,script:范圍在模塊之間共享 -$script:Variable在一個模塊函式中寫入將導致非本地$Variable決議在同一模塊中的任何其他函式中正確決議
有關范圍變數決議的更多資訊,請參閱幫助about_Scopes檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/511304.html
標籤:电源外壳变量范围喜好
