解释 PowerShell 函数中的变量/数组作用域。
powershellmicrosoft technologiessoftware & coding更新于 2026/1/8 7:07:17
通常,当变量在脚本中声明为公共变量或在函数外部(不在任何其他变量或条件中)时,无需将该值传递给函数,因为函数在调用之前初始化变量时会保留变量的值。
示例
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 数组变量的值为空,并且函数无法更新原始变量。

