Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Referencing a single element in an Array

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?

like image 852
Theunis Avatar asked Jul 14 '20 20:07

Theunis


People also ask

How do you reference one element in an array?

So array2[1][3] would be referencing the element of the index of row 1, column 3 (the 2nd row and the fourth column). Another notation that you can use to reference an element of an array is to use a single opening and closing brackets.

How do you access an array element in PowerShell?

To access items in a multidimensional array, separate the indexes using a comma ( , ) within a single set of brackets ( [] ). The output shows that $c is a 1-dimensional array containing the items from $a and $b in row-major order.

How do you assign a value to an array in PowerShell?

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.

How do I get the first element of an array in PowerShell?

Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].


1 Answers

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.

like image 190
mklement0 Avatar answered Oct 22 '22 11:10

mklement0