First post, I’ve been researching this all day and I’m at my wits end! I have an array called $Global:CBCGroups that I want to contain the value of an ever-changing variable called $Global:CBCTempHolder. Whenever $Global:CBCTempHolder is changed, I want it to add it’s contents to the array $Global:CBCGroups using += (ie:
$Global:CBCGroups += $Global:CBCTempHolder
The columns in CBCGroups are CBCGroup, and Element. The same is present in $Global:CBCTempHolder, but the value changes in every “For” statement. Here is the code:
$Global:CBCGroups = @()
for ($z = 0; $z -lt $Global:UniqueCCData.count; $z +=1)
{
If ($Global:UniqueCCData[$z]."AD Group".Contains("CBC_CBC_") -eq $True)
{
$Global:CBCTempHolder = @(0) * 1 | select CBCGroup,Element
$Global:CBCTempHolder.CBCGroup = $Global:UniqueCCData[$z]."AD Group"
$Global:CBCTempHolder.Element = $z
$Global:CBCGroups += $Global:CBCTempHolder
$Global:UniqueCCData[$z]."AD Group" = $Global:UniqueCCData[$z]."AD Group".Replace("CBC_CBC_","CBC.CBC")
}
}
So, basically what is happening is whenever I add a new element to $Global:CBCGroups via:
$Global:CBCGroups += $Global:CBCTempHolder
I am noticing that whenever I change the value of $Global:CBCTempHolder and then manually change the values of $Global:CBCTempHolder.CBCGroup to anything, add say 5 elements in a row using the assign by addition operator, and then change the value of $Global:CBCTempHolder again manually, it changes the last 5 elements in $Global:CBCGroups to the same value! I need each element in $Global:CBCGroups to maintain it’s value from the time when it was added to the array.
I realize $Global:CBCTempHolder is not a true array, but it contains the two named elements that I need to have added to a new list. How can I achieve this?
Here’s code that exhibits the issue:
Here’s the output:
The problem is that a reference to the object is assigned. So when the object changes, any objects that are referencing it also appear to change. The way to work around this to assign unique objects to each index of CBCGroups. Here’s how I’d solve it:
This produces the desired output: