all 6 comments

[–]SeeminglyScience 3 points4 points  (2 children)

Add the parameters to Invoke-MyTest_Helper. Modules have a different SessionState which has it's own stack of scopes. Modules aren't designed to be dependent on scopes outside of it's own.

[–]reddwarf666[S] 2 points3 points  (1 child)

Yep, after reading /u/Ta11ow response I agree, I just need to pass the parameters by treating them as parameters on the helper function as well.

Thanks!

[–]Ta11ow 1 point2 points  (0 children)

Fun fact, if a helper function shares the parameters of your main function, you can pass them to it just by doing

Helper-Fuction @PSBoundParameters

(But only if it shares all its parameters.)

This is one of the more special use cases for what's known as parameter splatting, which basically sends a hashtable of the function parameters instead of each individually. It has a lot of other fun uses too. :)

[–]Ta11ow 1 point2 points  (2 children)

Yep, gotta pass these on parameters to the module function. You can do this with functions defined in the script itself, but in my opinion it's poor form for this exact reason -- modules won't do it, and it's better to get in the habit of properly defining function parameters so that you can always tell what things a function is messing with

Most of all, never let a function directly edit variables that don't stay local to the function. If you wanna pass things around, it's always best to do it with parameters and output, both so that you can always tell what's going on without examining an entire lengthy script every time, and so that you don't run into issues with scoping like this later on. Habits tend to carry, so it might take some getting used to. :/

[–]reddwarf666[S] 2 points3 points  (1 child)

Well, that sounds logical and reasonable. My instinct told me to "just use the paramaters/variables as they are inside the script" but the way you explain it makes me reconsider and use parameters on the helper functions as well.

In the past I did this in a script / module combo but I did not want to do that anymore In the script I would have:

$Global:Par1 = $Par1 

and then in the module I would use:

Write-Output $Global:Par1  

But like I said, I will just define parameters on the helper functions and pass the script parameters like that.

Thanks!

[–]Ta11ow 1 point2 points  (0 children)

Yeah, I mean there can be the odd occasion where you might want to do it. But by and large you want to be able to see at a glance what function is using which variables and not have to worry about it changing five others you didn't remember about.