在另一個腳本內部調用的PowerShell腳本將有權訪問父腳本的變量,但任何修改都將丟失,因爲它們保存在本地範圍中(請閱讀更多about scopes here)。
Parent.ps1
$MyVariable = "Foo"
Write-Host "PARENT BEFORE: MyVariable: $MyVariable"
& "$PSScriptRoot\Child.ps1"
Write-Host "PARENT AFTER: MyVariable: $MyVariable"
Child.ps1
Write-Host "CHILD BEFORE: MyVariable: $MyVariable"
$MyVariable = "Bar"
Write-Host "CHILD AFTER: MyVariable: $MyVariable"
輸出:
PS > .\Parent.ps1
PARENT BEFORE: MyVariable: Foo
CHILD BEFORE: MyVariable: Foo
CHILD AFTER: MyVariable: Bar
PARENT AFTER: MyVariable: Foo
如果使用點採購(.
)來調用子腳本,它將運行在父腳本的作用域中,該腳本將在子腳本中對t可見的變量進行修改他的父母。例如:
Parent.ps1
$MyVariable = "Foo"
Write-Host "PARENT BEFORE: MyVariable: $MyVariable"
. "$PSScriptRoot\Child.ps1"
Write-Host "PARENT AFTER: MyVariable: $MyVariable"
輸出:
PARENT BEFORE: MyVariable: Foo
CHILD BEFORE: MyVariable: Foo
CHILD AFTER: MyVariable: Bar
PARENT AFTER: MyVariable: Bar
在PowerShell中的 '點採購' 讀了起來,我覺得這是你以後 – arco444
謝謝。點源是我一直在尋找的。 – MikePro