I'm working on a script where I'm iterating through a list of servers to get specific metrics and trying to store those values in an array. While the initial iteration works fine and displays the metrics, I encounter an error on the second loop when I attempt to update the array. Here's a snippet of what I'm using to create or update the array:
`$results += [PSCustomObject]@{`
`Server=$server`
`Metric=$metricKey`
`Value=$metricValue`
`}`. Any suggestions on how to fix this issue?
4 Answers
Have you double-checked if you've run `$results = @()` to initialize the array? It’s a common mistake that can lead to the issues you're facing.
Using `+=` isn't the best practice for building arrays in PowerShell, especially for larger datasets. Instead, consider creating the array directly in the loop like this:
`$arrayVar = @(
foreach ($thing in $things) {
[pscustomobject]@{
Server = $server
Metric = $metricKey
Value = $metricValue
}
}
)`
This approach is more efficient.
You should definitely include the error message you're getting when things fail. That can provide crucial insights. Also, sharing the entire script might help others identify the exact issue, though I understand if you can't due to work restrictions.
Good point! I fixed the catch to output the error message. It says: Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named 'op_Addition'.
It sounds like you're missing the initialization of the array. Before you start adding items, make sure you've initialized it with `$results = @()`. If you're running this inside a loop, consider using a `foreach` loop instead of `+=` to avoid performance issues. This way, you can build the array without resizing it every time.
Boom, initialization is what I missed! Thanks for pointing that out. I'll try the `foreach` method you suggested since I'm actually doing nested loops.
Argggghhhh! I always forget to initialize. Thank you!