Store output of ForEach into array in powershell
26,454
Solution 1
$FinalResult = @()
$data = @("server1","server2","server3")
foreach ($server in $data) {
$results = (Test-Connection $server -count 1 | Measure-Object -Property ResponseTime -Average).Average
$FinalResult += New-Object psobject -Property @{
ServerName = $server
Result = $result
}
}
$FinalResult | Select ServerName, Result | Export-Csv ".\FinalResult.csv" -NoTypeInformation
Please let me know if this snippet doesn't work, i will do the needful.
Solution 2
By doing the ForEach
, you're just measuring the value of the property of a scalar (single) object. The average will always be just the value of that property.
Test-Connection
will accept an array of names as the -ComputerName parameter, so the ForEach isn't really necessary at all.
$data = @("server1","server2","server3")
$results = Test-Connection $data -count 1 | select -ExpandProperty ResponseTime
Author by
Aaron
Updated on July 09, 2022Comments
-
Aaron almost 2 years
$data = @("server1","server2","server3") foreach ($server in $data) { $results = (Test-Connection $server -count 1 | Measure-Object -Property ResponseTime -Average).Average }
I'm trying to figure out how to take the output of a ForEach and store the results into an array so I may then compare them later. I could not come up with a way to do this yet.