PowerShell的数组范围;为什么我的数组是空的? [英] Powershell array scope; why is my array empty?
问题描述
我想有一个数组,并从不同的功能在我的脚本元素添加到它。我下面的例子说明了,我可能会被误解有关范围的东西。我的理解是目前,如果一个数组定义在函数外,再元素里面的功能增加,这些元素应该是可用的功能外。
I want to have an array and add elements to it from different functions in my script. My example below illustrates where I might be misunderstanding something regarding scope. My understanding currently is that if an array is defined outside the function, and then elements are added inside the function, those elements should be available outside the function.
Function ListRunningServices
{
$services+= Get-Service | ?{$_.Status -eq "Running"} | sort Name | select Name;
}
$services = @();
ListRunningServices;
$services;
我缺少的是在这里吗?也许我的风格是完全错误的。
What am I missing here? Perhaps my style is completely wrong.
推荐答案
在功能块内的 $服务
的作用域的功能。你可以做这样的事情,而不是以下内容:
The $services
within the function block is scoped to the function. You can do something like the following instead:
Function ListRunningServices {
Get-Service | ?{$_.Status -eq "Running"} | sort Name | select Name
}
$services = ListRunningServices
$services
否则,你可以明确地使用全球
来改变范围:
Function ListRunningServices {
$global:services = Get-Service | ?{$_.Status -eq "Running"} | sort Name | select Name
}
$services = @()
ListRunningServices
$services
这篇关于PowerShell的数组范围;为什么我的数组是空的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!