0

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
3
  • You're not returning $var. Commented Oct 3, 2019 at 14:39
  • @DanielMann if I type "return($var)", it only outputs $var, it does not change the variable when it actually returns. Commented Oct 3, 2019 at 14:41
  • @Aaron variables in powershell are locally scoped, meaning that changing the value of a variable with the name var inside two won't change the value of var inside the calling scope Commented Oct 3, 2019 at 14:50

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to do this if you call another function and that function has 2 or more variables in it? I know you set $var = two , so say function two has 2 variables in it, how do you get them back?
$var1,$var2 = two
@Aaron Might be worth reading this document as well - in PowerShell you don't need to specify the return keyword in order to pass data back to the caller (which may be slightly confusing at first)
0

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.

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.