解釋 PowerShell 函式中的變數/陣列作用域。


通常,當變數宣告為公共變數或在指令碼中函式外部宣告(不在任何其他變數或條件中)時,不需要將該值傳遞給函式,因為在呼叫函式之前初始化變數時,函式會保留變數的值。

示例

function PrintOut{
   Write-Output "your Name is : $name"
}
$name = Read-Host "Enter your Name"
PrintOut

在上面的示例中,**$name** 變數是在名為 **PrintOut** 的函式外部宣告的。因此,由於可以在函式內部讀取該變數,可以直接使用其名稱來使用該變數。

輸出

Enter your Name: PowerShell
your Name is : PowerShell

相反,如果在函式內部宣告 **$name** 變數,並在函式外部檢查輸出,則不會獲得變數的值。

示例

function PrintOut{
   $name = Read-Host "Enter your Name"
}
PrintOut
Write-Output "your Name is : $name"

輸出

Enter your Name: PowerShell
your Name is :

在上面的輸出中可以看到,**$Name** 的值為 **NULL**,因為 $name 是在函式內部宣告的。

另一方面,如果變數或陣列是在函式外部宣告的,並且在函式內部修改變數或陣列的值,則它不會反映在函式外部。

示例

function PrintOut{
   $name = Read-Host "Enter your Name"
   Write-Output "Name inside function : $name"
}
$name = "Alpha"
PrintOut
Write-Output "Name after calling function : $name"

輸出

Enter your Name: PowerShell
Name inside function : PowerShell
Name after calling function : Alpha

正如我們在這裡觀察到的,**$name** 變數的值在函式內部發生變化,但不會反映在函式外部,因為它具有有限的作用域。

類似地,對於陣列,

$services = @()
function Automatic5Servc{
   $services = Get-Service | Where{$_.StartType -eq "Automatic"} | Select -First 5
}
Automatic5Servc
Write-Output "Automatic Services : $services"

在上面的程式碼中,您將無法獲得服務資訊,因為 Services 陣列變數的值為空,並且函式無法更新原始變數。

更新於:2020年4月17日

228 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告