Thursday, January 30, 2014
PowerShell - .CLONE method on non-primitive variables
When making copies of non primitive variables such as arrays, you my not get what you expect if you assign one variable with the value of another. Run this script to illustrate the issue:
# This may not do what you think
$array1 = "apples", "banana", "oranges"
$array2 = $array1
Write-Host "Array1 contains: $array1"
Write-Host "Array2 conatins: $array2"
Write-Host "`nNow changing second element of Array2 to strawberry"
$array2[1] = "strawberry"
Start-Sleep 4
Write-Host "`nArray2 contains: $array2"
Start-Sleep 4
Write-Host "`nBut horror! Array1 has changed as well"
Write-Host "`nArray1 contains: $array1"
Start-sleep 4
This occurs because the second array is just a memory reference to the first array. You c an change this behavior by using the CLONE method thus:
# Clone method
Write-Host "`nNow use the clone method to repeat the experiment"
Start-Sleep 4
$array1 = "apples", "banana", "oranges"
$array1 = "apples", "banana", "oranges"
$array2 = $array1.Clone()
Write-Host "Array1 contains: $array1"
Write-Host "Array2 conatins: $array2"
Write-Host "`nNow changing second element of Array2 to strawberry"
$array2[1] = "strawberry"
Start-Sleep 4
Write-Host "`nArray2 contains: $array2"
Start-Sleep 4
Write-Host "`nYea! Array1 has been preserved"
Write-Host "`nArray1 contains: $array1"
Start-sleep 4
Write-Host "`nNow use the clone method to repeat the experiment"
Start-Sleep 4
$array1 = "apples", "banana", "oranges"
Cheers!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment