Home powershell looping and storing content to variable
Reply: 4

powershell looping and storing content to variable

cata
1#
cata Published in 2017-11-03 13:28:59Z

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!

Mathias R. Jessen
2#
Mathias R. Jessen Reply to 2017-11-03 14:05:28Z

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
})
Bryce McDonald
3#
Bryce McDonald Reply to 2017-11-03 13:34:26Z

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
dan6657
4#
dan6657 Reply to 2017-11-03 13:39:12Z

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..

Bill_Stewart
5#
Bill_Stewart Reply to 2017-11-03 14:25:17Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.278488 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO