powershell looping and storing content to variable

Viewed 17719

So I need my script to loop through an array and store the content in other variable, so I can manipulate it later.

foreach ($element in $machinesNames){
Get-BrokerMachine -MachineName $element | select LoadIndex -expand LoadIndex
}

OUTPUT:

2845
5750
5875
5944
5873
5828
5205
6302
5025
5655
6311
5626
5491
5621

How can I store above results in an array?

Thanks!

4 Answers

You can assign the output from a loop construct directly to a variable:

$result = foreach($element in $machinesNames){
    Get-BrokerMachine -MachineName $element | select LoadIndex -expand LoadIndex
}

If you want to make sure that you always end up with an array, wrap the expression in an array subexpression operator @():

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

You can initialize an array by setting $myvar = @() then within your foreach loop add the content of your query to myvar. Your code will look like this:

$myvar = @()
foreach ($element in $machinesNames){
$myvar += Get-BrokerMachine -MachineName $element | select LoadIndex -expand LoadIndex
}
return $myvar

You could initialize and add to an arraylist within your loop such as:

$ArrList = [System.Collections.ArrayList]@()

$ArrList.Add(Get-BrokerMachine -MachineName $element | select LoadIndex -expand LoadIndex)

then return it anywhere..

You can also use ForEach-Object to accumulate a list:

$results = $machineNames | ForEach-Object { Get-BrokerMachine -MachineName $_ | Select-Object -ExpandProperty LoadIndex }

If there is one output, it will be a single element; otherwise it will be a collection. If you want to ensure it's a collection:

$results = @($machineNames | ForEach-Object { Get-BrokerMachine -MachineName $_ | Select-Object -ExpandProperty LoadIndex })

I tend to like this solution because it's a single assignment statement.

Related