Your company's ad could live here and reach over 50,000 people a month!

Share This Post

PowerShell Mistake: Expecting By Value And Getting By Reference

The script I wrote to parse the client health log files had a bug in it where if a computer reported multiple status codes the output would only include the last status code. This is because I was adding the values to the array by reference, changing the object, and adding it again by reference. Since both indexes of the array were referencing the same object in memory I was ending up with only the last status code. Oops. What I meant to do was add the value of the object to the array, modify the object, and then add the new value to the array.

Old code:


    for ($i=4;$i -lt $lines.Length;$i++) {
        $status = $lines[$i].Split("|")
        $computer.StatusCode = $status[0]
        $computer.StatusDescription = $statusCodes[$status[0]].Description
        $computer.Date = $status[1]
        $results += $computer


And what I meant to do was this:

$results += ($computer | select *)

If there is a more elegant way to do this I’d be interested in knowing.

The script in my last blog post has been updated.

Share This Post

Leave a Reply