0

Here is my code:

$problems = New-Object System.Collections.ArrayList

$problemObj = New-Object psobject -Property @{
    problemName        = "abc"
    problemDescription = $null
}

$problemObj.problemDescription = "def"
$problems.Add($problemObj)

$problemObj.problemDescription = "ghi"
$problems.Add($problemObj)

$problems

And here is the output:

problemName problemDescription
----------- ------------------
abc         ghi
abc         ghi

I don't get what's wrong and why the first member gets modified. Any idea?

Thanks,

  • 1
    Does this answer your question? [How to create new clone instance of PSObject object](https://stackoverflow.com/questions/9581568/how-to-create-new-clone-instance-of-psobject-object) – OwlsSleeping Jan 11 '22 at 10:35
  • 1
    Just to add a bit of detail on the duplicate flag- your problem is that PsObject copies by reference rather than value. – OwlsSleeping Jan 11 '22 at 10:36

1 Answers1

1

You're not creating new objects - you're modifying and re-adding the same object to the list multiple times.

A common pattern for solving this is to re-use a dictionary as a template, then cast to [pscustomobject] to create new objects based on it:

$problems = New-Object System.Collections.ArrayList

# Create ordered dictionary to function as object template
$problemTemplate = [ordered]@{
    problemName        = "abc"
    problemDescription = $null
}

# modify template
$problemTemplate.problemDescription = "def"

# create new object, add to list
$problemObj = [pscustomobject]$problemTemplate
$problems.Add($problemObj)

# modify template again
$problemTemplate.problemDescription = "ghi"

# create another object, add to list
$problemObj = [pscustomobject]$problemTemplate
$problems.Add($problemObj)

$problems
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206