0
 function test1{
     param([System.Collections.ArrayList]$x
     )
     $x.Add("Test1Add")
     write "in Test1 $x"
 }
$x=New-Object System.Collections.ArrayList

Here is my code , after I run test1, Result would be:

PS C:\Windows> test1 $x
0
in Test1 Test1Add

PS C:\Windows> $x
Test1Add

I am wondering why this happens, I guess when invoke test1, It just like passing a pointer of a Reference type to test1, Just like C# or other language? Value type like int, I must use $script:x to change the x in the gloabl scope . Thanks in advance

2
  • What are you expecting to happen? Commented Apr 15, 2015 at 9:36
  • I first tested the [int] type parameter, a value type, the x in the global scope didn't change. Then I tried this, found it changed, So I want to know if my guess is correct Commented Apr 16, 2015 at 1:08

1 Answer 1

1

Use Reference variables:

  $x=New-Object System.Collections.ArrayList
  function test( [ref][System.Collections.ArrayList]$x) { $x.value.Add($(get-random)) }
  test ([ref]$x)
  test ([ref]$x)
  $x

EDIT

I misunderstood the question, you wanted the opposite. The result is the same in above case but not for value types. If you want above function not to change the referenced object you need to clone it inside the function. There may be a Clone function, but in some cases you will have to manually create the clone. In this case there is such method so you can add $x=$x.Clone() at the start of the above function to get the desired result.

Value types are passed as value and other things are passed as reference. The easiest way to check if var is of ValueType is to do $var.GetType().IsValueType.

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

1 Comment

Hi, thank you for your help! [ref] would be a great help for the value type parameter, didn't know this before. But in this case, even without using the reference variable, the variable x will change. So I guess if the variable contains an Reference type object, it doesn't need the [ref]. Am I right?

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.