'Return variable from one function to another in powershell

I am inside function #1 and triggering function #2. Function #2 has a variable that I want to get back into function #1 and use it.

My output ends up being:

hey there
var is:

What I want is the output to be:

var is: hey there

Why is it that I can feed a function a variable, and it uses it, but when I change that variable in the #2 function, it does not change the variable after it returns?

$var = $null

function one() {

two($var)

write-host "var is:" $var

}


function two($var){

$var = "hey there"

return($var)

}

clear
one


Solution 1:[1]

First, change your two function to actually return a value:

function two {
  $var = "hey there"

  return $var
}

and then update the one function to actually "capture" the output value by assigning it to a variable:

function one {
  # PowerShell doesn't use parentheses when calling functions
  $var = two

  Write-Host "var is:" $var
}

Solution 2:[2]

If you really do want to reach up and change a variable in the scope of your caller, you can...

Set-Variable -Name $Name -Value $Value -Scope 1

It's a little meta/quirky but I've run into cases where it seemed proper. For example, I once wrote a function called RestoreState that I called at the beginning of several functions exported from a module to handle some messy reentrant cases; one of the things it did is reach up and set or clear $Verbose in the calling function's scope.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias R. Jessen
Solution 2 PreventRage