20

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ed Manet
  • 3,118
  • 3
  • 20
  • 23

3 Answers3

29

Call like this:

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

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

Community
  • 1
  • 1
manojlds
  • 290,304
  • 63
  • 469
  • 417
25

By the way, PowerShell has a special syntax to swap values, and there isn't a need to use $tmp:

$a,$b = $b,$a
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
3

Firstly, you're calling it wrong. Putting a comma in the call to swap means you're passing an array of them to objects as the first parameter. If you were to correct it...

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

...it would then work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Joel B Fant
  • 24,406
  • 4
  • 66
  • 67