Powershell array assignment assigns variable, not value?

I have an example program that creates an array and then tries to assign the value of this array several times to another array as a multidimensional array.

$a =@(0,0,0)
$b = @($a,$a,$a)
$b[1][2]=2
$b
'And $a is changed too:'
$a

Conclusion:

PS E:\Workarea> .\what.ps1
0
0
2
0
0
2
0
0
2
And $a is changed too:
0
0
2

So, in this case, the variable actually points to the original variable. This is a very unexpected behavior. It's pretty neat that you can do this, although I never used unions in my C programming. But I would like to really just assign a value, not a variable.

$b = @($a.clone(),$a.clone(),$a.clone())

I think it would work, but something tells me that there might be something more elegant than that.

Thanks for the input.

This is PowerShell 2.0 under the 64-bit version of Windows 7.

+5
source share
2

$a $b $a, $(). , $(), , $($a) 0, 0, 0.

$a =@(0,0,0)
$b = @($($a),$($a),$($a))
$b[1][2]=2
$b
'$a is not changed.'
$a
+4

PowerShell ',' , . , , , :

$a= new-object ‘object[,]’ 3,3
$a[0,2]=3 
PS > for ($i=0;$i -lt 3;$i++)
>> {
>> for($j=0;$j -lt 3;$j++)
>> {
>> $a[$i,$j]=$i+$j
>> }
>> }

$b - .

+1

All Articles