Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell pass by reference not working for me

I'm trying to make a simple swap function in PowerShell, but passing by reference doesn't seem to work for me.

function swap ([ref]$object1, [ref]$object2){
  $tmp = $object1.value
  $object1.value = $object2.value
  $object2.value = $tmp
}

$a = 1
$b = 2
$a, $b
swap ([ref]$a) ,([ref]$b)
$a, $b

This SHOULD work, but no...

Output:
    1
    2
    1
    2

What did I do wrong?

like image 477
Ed Manet Avatar asked Aug 22 '11 15:08

Ed Manet


People also ask

How do you pass by reference in PowerShell?

To pass a variable to a parameter that expects a reference, you must type cast your variable as a reference. The brackets and parenthesis are BOTH required.

How do I pass a PowerShell script?

If you then want to pass a string as parameter you can use either ' or " . If there is no space (or quotes) inside the string you can even omit the quotes.

How do I pass multiple arguments in PowerShell script?

To pass multiple parameters you must use the command line syntax that includes the names of the parameters. For example, here is a sample PowerShell script that runs the Get-Service function with two parameters. The parameters are the name of the service(s) and the name of the Computer.

How do you return a value from a function in PowerShell?

The return keyword exits a function, script, or script block. It can be used to exit a scope at a specific point, to return a value, or to indicate that the end of the scope has been reached.


1 Answers

Call like this:

swap ([ref]$a) ([ref]$b)

The mistake of using , is described in the Common Gotchas for PowerShell here on Stack Overflow.

like image 193
manojlds Avatar answered Oct 12 '22 21:10

manojlds