Reputation: 75
I would like to reference a single element inside an array, using the [ref] keyword.
How to test for a reference:
$var1 = "this is a string"
[ref]$var2 = [ref]$var1
$var2.Value
this is a string
$var2.Value += " too!"
$var2.Value
this is a string too!
$var1
this is a string too!
The above is working as expected. But now to reference a single element inside any array?
$var3="string 1", "string 2", "string 3"
[ref]$var2=[ref]($var3[1])
$var2.Value
string 2
$var2.Value += " updated!"
$var2.Value
string 2 updated!
$var3[1]
string 2
I expected $var3[1]
to return the same as the value of $var2.Value
. What am I doing wrong?
Upvotes: 6
Views: 2955
Reputation: 437833
In PowerShell, you cannot obtain a reference to individual elements of an array.
To gain write access to a specific element of an array, your only option is:
to use a reference to the array as a whole
and to reference the element of interest by index.
In other words:
Given $var3 = "string 1", "string 2", "string 3"
, the only way to modify the 2nd element of the array stored in $var3
is to use $var3[1] = ...
(barring acrobatics via C# code compiled on demand).
As for what you tried:
[ref] $var2 = [ref] ($var3[1])
In PowerShell, if you get the value of $var3[1]
, it is invariably a copy of the data stored in $var3
's 2nd element (which may be a copy of the actual data, if the element contains an instance of a value type, or a copy of the reference to the instance of a reference type, otherwise).
Casting that copy to [ref]
is therefore invariably disassociated from the array element of origin.
Upvotes: 4