Help with PowerShell Array Updates

June 10, 2025 4 answers
Asked by TechieNomad42
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?

Answers

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

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

Reply to this answer
ScripterQueen
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.

TechieNomad42: 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'.

Reply to this answer
CodeWhisperer
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.
Reply to this answer
ArrayNinja
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.

TechieNomad42: Argggghhhh! I always forget to initialize. Thank you!

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions