Function of Functions – pass variable between scopes – powershell

I am looking to create a some functions that create a result in a variable within the scope of a function and then pass that variable from one function to another function. as a simplified example, say I wanted the test1 function to combine two strings and then have another function that can take an action on that combined string. How would I do that? I know I could always put the function call of test two within the function of test1 but, that could get messing and confusing if I had several functions I needed to do that with. Is there a way to get that variable to be saved outside the scope of test1 function so test 2 can use it when called from a third function? My thoughts are that I need to do several different tasks that will be handled by different functions and then have a main function (funcOfFuncs in this example) that would call the functions when needed based on different criteria. Would I need a global variable or is there a way to pass that $t1combine back out of test one to be used later? I tried utilizing return but that did not work.

$test1a = "foo"
$test1b = "bar"


function test1 {
    param (
    $test1a, 
    $test1b
    )
    $t1combine = $test1a + $test1b
    Write-host "We are in test func 1"
    write-host $test1a " ... " $test1b
    Write-host $t1combine
}

function test2 {
    param ($t1combine)
    write-host "Inside test 2 func....." $t1combine
}


function funcOfFuncs{

test1 $test1a $test1b
test2 $t1combine
}

funcofFuncs

I know the above will not work as $t1combine is in the test1 function scope. I attempted making a separate variable outside of all functions and setting equal to the function ($x = test1) but that did not work. I tried adding return $t1combine to the test1 function but that did not work for making the $t1combine available outside the test1 function. Any assistance that can be provided would be greatly appreciated!

>Solution :

I would do a bit more reading up on how Functions work (e.g. PowerShell 101 Functions), as it will help you complete what you are trying to do.

Basically you don’t have to resort to global variables. You are missing 2 things from your example. Instead of Write-Host which writes out to the screen, you use Write-Output to "return" values back from the function. And second, you need to take the return value and store it in a variable (e.g. $t1combine).

Here is the example code:

$test1a = "foo"
$test1b = "bar"

function test1 {
    param (
    $test1a, 
    $test1b
    )
    $t1combine = $test1a + $test1b
    Write-host "We are in test func 1"
    write-host $test1a " ... " $test1b
    Write-Output $t1combine
}

function test2 {
    param ($t1combine)
    write-host "Inside test 2 func....." $t1combine
}


function funcOfFuncs{

$t1combine = test1 $test1a $test1b
test2 $t1combine
}

funcofFuncs

Leave a Reply