mayen
mayen

Reputation: 132

References to arrays/objects in PowerShell

I use the reference Variable to pass parameters to functions and to manipulate values across functions using the same base variable.

For my other script this worked fine, and maybe this is just a thought problem here, but why this isn't working?:

$Script:NestedLists = @("test", @("test_level_2"))

function AddToReference
{
    param([ref]$RefVar)
    $RefVar.Value += @("hi")
}

AddToReference -RefVar ([ref]($Script:NestedLists[1]))

$Script:NestedLists[1]

I thought the output of $Script:NestedLists[1] would be "test_level_2" and "hi" but it is just "test_level_2"

Upvotes: 1

Views: 93

Answers (1)

Robert Cotterman
Robert Cotterman

Reputation: 2268

This little change made it work

$Script:NestedLists = @("test",@("test_level_2"))

function AddToReference
{
    param ([ref]$RefVar) ($RefVar.value)[1] += , "hi"
}

addtoreference ([ref]$Script:NestedLists)

$Script:NestedLists[1]

Why moving the [1] to $refvar made it work, I have no idea, I wish I had a better understanding. Also, this get's really tricky because if you add a value to the first array in the $script it moves the [1] to [2] etc...

I would personally do something to keep each array separate, and at the end just combine them as needed...

$a = "first","array"
$b = "second","array"
$script:nested = $null
$script:nested += , $a
$script:nested += , $b

The "+= ," combines each array in a nested array. so [0] would equal $a and [1] would equal $b

Upvotes: 1

Related Questions