2

I like C# so much better than PS but this time I'm forced to write a script... I need to alter "global" variable from inside a function without passing the variable as parameter. Is it even possible? Here is an abstract:

$a = 0
$b = 0
$c = 0
function Increment($var1, $var2)
{
$a = $var1
$b = $var2
$c++
}

Unlike C# in PS function variable are function scope bound and they remain unchanged outside of the scope of the function if used as described above. How can I make this work so the script variable are accessed by reference?

3
  • Possible duplicate of How to modify parent scope variable using Powershell. Commented Nov 6, 2014 at 16:47
  • 3
    Use $script:a $script:b etc.... Commented Nov 6, 2014 at 16:50
  • In general this violates the purpose of a function (alter variables outside of its own scope). You can modify variables in a parent scope, but there are usually other ways to solve the problem. Keep in mind that PowerShell can return multiple values from a function. Commented Nov 6, 2014 at 17:27

2 Answers 2

4

Try using the PowerShell global variable definition:

$global:a = 0
$global:b = 0
$global:c = 0
function Increment($var1, $var2)
{
    $global:a = $var1
    $global:b = $var2
    $global:c++
}
Sign up to request clarification or add additional context in comments.

Comments

3

If you really need to modify by reference, you can use [Ref], e.g.:

$a = 1
function inc([Ref] $v) {
  $v.Value++
}
inc ([Ref] $a)
$a  # outputs 2

Comments

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.