2015-03-02 111 views
0

我試圖瞭解變量如何保留值和範圍。爲此我創建了兩個簡單的腳本。瞭解PowerShell變量範圍

低級別的腳本看起來像這樣

param(
    $anumber=0 
) 

function PrintNumber 
{ 
    Write-Host "Number is $anumber" 
    $anumber++ 
    Write-Host "Number is now $anumber" 
} 

頂層腳本看起來像這樣

$scriptPath=(Split-Path -parent $PSCommandPath)+"\" + "calledscript.ps1" 
#dot source the called script 
. $scriptPath 22 

for($i=0;$i -lt 10;$i++) 
{ 
    PrintNumber 
} 

主腳本「點源」被調用的腳本一次,在一開始並傳遞一個值,「22」。然後我從頂層腳本中調用PrintNumber函數10次。我想輸出會是什麼樣子:

號是22 人數現已23

號是23 號是現在24

號是現在24 號是25

而是調用該函數時該數字始終爲22,(如下所示)。爲什麼這個數字每次重新設置爲22,即使我只拉了點源腳本一次,並將數字初始化爲22?

號是22 人數現已23

號是22 號是現在23

號是22 號是現在23

感謝

(請忽略任何錯別字)

+0

如果將其定義更改爲'$ global:anumber',會發生什麼情況? – arco444 2015-03-02 12:02:29

+0

我將參考(不是聲明)從$ anumber ++更改爲$ global:an ++ ++,然後按我的預期遞增。不完全確定爲什麼真的! – Keith 2015-03-02 13:52:13

+0

絕對是一個範圍界定問題。我不深入瞭解很多,但在PowerShell中有'local','script'和'global'變量。有意義的是,由於您從其他腳本獲取變量,所以默認範圍是'script',並且遞增的值不會持續。 – arco444 2015-03-02 14:11:14

回答

0

這是因爲變量繼承。 Technet是這樣解釋的。

A child scope does not inherit the variables, aliases, and functions from 
the parent scope. Unless an item is private, the child scope can view the 
items in the parent scope. And, it can change the items by explicitly 
specifying the parent scope, but the items are not part of the child scope. 

由於腳本是點源的,它會創建一個本地會話的變量。當函數訪問具有相同名稱的變量時,它可以從父作用域讀取該變量,但隨後會創建一個本地副本,然後將其增量並隨後銷燬。

+0

感謝@JonC,但是什麼變量是從父範圍讀取的函數?我只在被調用的腳本中有變量,而不是父變量。 – Keith 2015-03-02 13:39:18

+0

另一個問題是,如何顯式指定父範圍? – Keith 2015-03-02 13:53:25

+0

https://technet.microsoft.com/en-us/library/hh847849.aspx涵蓋範圍的基礎知識。簡短的答案是使用像$ global:anumber或$ script:anumber這樣的修飾符。您還可以使用cmdlets的相對修飾符,如'get-variable -name anumber -scope 0',其中0是當前作用域,1是直接父對象,2是下一個父對象等等。 – JonC 2015-03-02 14:22:44