Powershell functions and variable scope

by Lembasts at 2012-10-02 18:39:49

Greetings,
I have several functions which need to update variables defined in the parent scope. One option is to use the prefix like global: before each variable but that looks messy. Alternatively, I could pass the variables as parameters. I thought that parameters that were passed to functions were "by reference" so then whatever I changed in the function would change the parent scope variable value. I wanted to test this with the following code:
function tst($a,$b) {
$a++
$b++
}

$a = 0
$b = 0
tst $a $b
write-host "$a $b"

However, this writes out zero for both $a and $b.
So how can I pass parameters "by reference" please? What am I missing?

Cheers

David
by poshoholic at 2012-10-02 18:51:14
Pass by reference like this:
function tst {
param(
[REF]$a,
[REF]$b
)
$a.Value++
$b.Value++
}
$a = 0
$b = 0
tst ([REF]$a) ([REF]$b)
write-host "$a $b"
by Lembasts at 2012-10-02 18:59:40
Thanks for your quick reply.
This is going to make my code look awfully ugly as I have a number of variables to update and update them many times within the function.
I think I might be better off without parameters and using the $script: prefix.
Is there any neater solution where you have a function that needs to modify many parent variables many many times?
by Lembasts at 2012-10-02 19:11:04
I think I found my answer. I can just call my functions with the prefix ". ". So dot-sourcing my functions place them in the same scope as the parent!
by poshoholic at 2012-10-02 19:18:42
Yes, dot-sourcing works. If you don’t want to dot-source, you could always perform calculations inside a function and set variable values in the parent scope using:
Set-Variable -Scope 1 -Name VariableName -Value NewValue
by mjolinor at 2012-10-03 19:32:16
Another option is to replace your variables with a hash table. Variable assignments in a child scope creates a new variable, but assigning values to a hash table entry do not. You can take your existing variable names and make those the key names of a hash table in the parent scope, and then update the values directly within the functions without worrying about scope.
by Lembasts at 2012-10-03 21:21:33
Thanks. dot-sourcing seems the simplest as I am not only accessing variables but loads of objects and properties defined in the parent.