Suman Ghosh
Suman Ghosh

Reputation: 1539

Want to store output in an array

I have a list of servers. I want to check what all automatic services are not running. I want to store it in array and later display in grid view format. I tried below, but it didn't work.

foreach ($i in $list) {
    $Res = @(Get-WmiObject Win32_Service -ComputerName $i | Where-Object {
               $_.StartMode -eq 'Auto' -and $_.State -ne 'Running'
           } | Select PSComputerName, Name, DisplayName, State, StartMode)
}

$Res | Out-GridView

Upvotes: 0

Views: 901

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200283

Assigning values to $Res inside the loop overwrites the value with every loop cycle. for a construct like that you'd need to define the variable as an array outside the loop and then append to it:

$Res = @()
foreach ($i in $list) {
    $Res += Get-WmiObject ...
}

However, this is bound to perform poorly. It's usually better to just assign the output generated in the loop to the variable:

$Res = foreach ($i in $list) {
    Get-WmiObject ...
}

Upvotes: 1

Related Questions