Powershell passing argument values to parameters and back

Question:

Alright. I’m attempting to complete a school assignment and cannot for the life of me figure this out. I’m trying to use powershell to pass values from one function to another making a “modular” type script. I can’t seem to figure out how to move the values out of the scope of the function without using the $script:xxxxx. Is there another way to move the values in powershell as a regular argument parameter pass by reference?

Here’s what I have:

The two values right after the inputGrams function should change each time the script is run but they don’t because of scope issues and passing the values. Anyone know how to properly pass those values back to the main function?

Answer:

Andy is on the right path but [Ref] are tricky and it is recommended to avoid them if you can.

As you said, the problem is scope. All your functions —except main— are called from main, therefore you need to make the variables available to these functions by setting them in main‘s scope, i.e. their parent scope, with Set-Variable or New-Variable.

Same point is valid when retrieving their values with Get-Variable.

PS: I hope I did not spoil your school assignment, just wanted to help out 😉

Source:

Powershell passing argument values to parameters and back by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply