I need some assistance please, to understand behavior of arrays and powershell loops. I have stumbled upon a strange array behavior, here is the issue and sample script:
# I create simple array
$item2 = New-Object Collections.ArrayList
# getting some sample data for array
$allitems = Get-ChildItem -Path "c:\" | select name,Attributes
#running loop
foreach ($item in $allitems){
# outputing iriginal array item
Write-Host $item
# addind to new array
$item2.Add($item)| Out-Null
# here is the issue I have - after I add member to my $item2 array
# it is replicated to also $allitems, I don't need this behavior
# to happen. Also I don't understand why it changes the original
# $item and $allitems. Am I creating array copy incorrectly ?
$item2[-1] | Add-Member -MemberType NoteProperty -name 'testproperty' -value 'testvalue'
write-host "$($item2[-1]) mod"
Write-Host $item
}
result of the script is this :
@{Name=rollback2.puc; Attributes=Archive} -> original entry
@{Name=rollback2.puc; Attributes=Archive; testproperty=testvalue} mod -> modified entry
@{Name=rollback2.puc; Attributes=Archive; testproperty=testvalue} -> original entry modified , why ?
Any help appreciated. Thanks
Get-ChildItem -Pathtwice