1

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"

1
  • No matter which constellation I try it doesn't work correctly :( Yes, it was simpler before but now where no simple datatypes are used, it makes problems. Maybe it never was designed for this purpose?! I read an article about variable shadowing if you wander down and calling functions from other functions. Just a hypothesis: but maybe some Add function is called by powershell and the result never gets directed to the original variable Commented Aug 14, 2018 at 12:48

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your efforts. I will take this into consideration. In my case it is unpractical to annotate the variables with indexes until the point where I want to add the value, but maybe thats the only option :)
You might just be able to keep each nest separate, and then finalize it at the end (or when needed). answer edited for what I mean.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.