解释 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 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.