powershell循环并将内容存储到变量

cat*_*lin 0 arrays variables powershell

所以我需要我的脚本循环遍历一个数组并将内容存储在其他变量中,所以我可以稍后操作它.

foreach ($element in $machinesNames){
Get-BrokerMachine -MachineName $element | select LoadIndex -expand LoadIndex
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

2845
5750
5875
5944
5873
5828
5205
6302
5025
5655
6311
5626
5491
5621
Run Code Online (Sandbox Code Playgroud)

如何将上述结果存储在数组中?

谢谢!

Mat*_*sen 7

您可以将循环结构的输出直接分配给变量:

$result = foreach($element in $machinesNames){
    Get-BrokerMachine -MachineName $element | select LoadIndex -expand LoadIndex
}
Run Code Online (Sandbox Code Playgroud)

如果要确保始终以数组结束,请将表达式包装在数组子表达式运算符中@():

$result = @(foreach($element in $machinesNames){
    Get-BrokerMachine -MachineName $element | select LoadIndex -expand LoadIndex
})
Run Code Online (Sandbox Code Playgroud)