I'm completely lost in a mind loop at the moment:
I wanted to solve the problem of passing an array to a function by value instead of reference and found this solution: Is Arraylist passed to functions by reference in PowerShell.
The .Clone()-method works as expected:
function testlocal {
param ([collections.arraylist]$local)
$local = $local.Clone()
$local[0] = 10
return $local
}
$local = [collections.arraylist](1,2,3)
'Testing function arraylist'
$copyOfLocal = testlocal $local
$copyOfLocal
'Testing local arraylist'
$local
Output:
Testing function arraylist
10
2
3
Testing local arraylist
1
2
3
But now I need to process the array's elements in a foreach-loop. What happens then is that the array does not get modified by the foreach-loop (???). I am at a loss to understand this, despite a lot of research. Could you please explain to me what is happening behind the scenes and how I can avoid this? I need to modify a copy of the original array within a function's foreach-loop. In my real script, the array consists of custom PSObjects, but the behavior is the same.
function testlocal {
param ([collections.arraylist]$local)
$local = $local.Clone()
$local[0] = 10
foreach ($item in $local) {
$item = 100
}
return $local
}
$local = [collections.arraylist](1,2,3)
'Testing function arraylist'
$copyOfLocal = testlocal $local
$copyOfLocal
'Testing local arraylist'
$local
Output is not changed by the foreach-loop:
Testing function arraylist
10
2
3
Testing local arraylist
1
2
3
UPDATE 2016-12-14 The tip with the for-loop works, but it turns out when using objects, the whole cloning-thing falls apart again:
function testlocal {
param ([collections.arraylist]$local)
$local = $local.Clone()
for($i = 0; $i -lt $local.Count; $i++){
$local[$i].Hostname = "newname"
}
return $local
}
$target1 = New-Object -TypeName PSObject
$target1 | Add-Member -MemberType NoteProperty -Name "Hostname" -Value "host1"
$target2 = New-Object -TypeName PSObject
$target2 | Add-Member -MemberType NoteProperty -Name "Hostname" -Value "host2"
$local = [collections.arraylist]($target1,$target2)
'Testing function arraylist'
$copyOfLocal = testlocal $local
$copyOfLocal | ft
'Testing local arraylist'
$local | ft
Output:
Testing function arraylist
Hostname
--------
newname
newname
Testing local arraylist
Hostname
--------
newname
newname
Suddenly I am back to passing by reference again. This is driving me mad! Please help!