Author Posts

June 9, 2015 at 12:38 pm

Can you please let me know if I can use the declared variable in the powershell script as the passing parameters to a function when it is declared and called in that script? I have few variables and I want to pass their values to multiple functions created in a powershell script rather than declaring parameters for every function separately.

Thanks
Devesh

June 9, 2015 at 1:28 pm

Uh.

OK. What I think you're asking is, "if I declare a variable in my script, can the functions also in that script 'see' that variable?"

The answer is, "probably, and maybe," but you may not understand about PowerShell scope. If you'd like to learn more about it, read about_scope in the shell's help system.

However, AS A BEST PRACTICE, you SHOULD NOT do what you're asking, whether the shell allows it or not. You SHOULD declare parameters for all of your functions. Functions should be entirely self-contained, meaning they get all of their input only from parameters, and they output only to the PowerShell pipeline. They don't "share" variables. Doing so makes functions dependent on that particular script, which is a Very Bad Practice.

Just declare parameters for every function separately. It's the right thing to do and will save you a lot of debugging time later on down the line.