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?
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.
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.
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.
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.
Call like this:
swap ([ref]$a) ([ref]$b)
The mistake of using ,
is described in the Common Gotchas for PowerShell here on Stack Overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With