Use values from a function and pass it to another function

Question:

I have the below two functions and I want the SOURCE and TARGET of the ROBOCOPY function used within the Comparision function. Can anyone tell me how to do this please. Thanks.

Answer:

Variables in powershell are context sensitive. If I define a function like:

Then the $bar variable is not available to me outside that function. To make variables available outside of functions then you can control the scope of a function. If I set a variable in a function using the script or global prefix then the variable will be available for the whole script or globally in powershell runspace. See here:

The variable $fooVar in the foo function will be available to all other functions within the script due to the scope prefix script of the variable $fooVar. The barVar function will be available globally in the runspace. I.e. when your script has finished the variable is still present back at the command line and even to other scripts.

As you can see in the bar function I first call foo and then use the foovVar variable. When I use the $fooVar variable I don’t have to specify the $script:fooVar, I can if I want to but it’s not necessary.

These are all valid variable assignments:

So in your case use $script:source and $script:target or $global:source and $global:target. For more info run the following command:

Source:

Use values from a function and pass it to another function by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply