Using Declared Variables As Passing Parameters to Multiple Functions

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Don Jones Don Jones 1 year, 4 months ago.

  • Author
  • #26219
    Profile photo of Devesh Srivastava.
    Devesh Srivastava.

    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.


  • #26223
    Profile photo of Don Jones
    Don Jones


    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.

You must be logged in to reply to this topic.