How to replace global variables?

Welcome Forums General PowerShell Q&A How to replace global variables?

This topic contains 2 replies, has 3 voices, and was last updated by

4 years, 8 months ago.

  • Author
  • #16407

    Points: 0
    Rank: Member

    I'm currently using global variables across multiple ps1 scripts (variables include logpath, loglevel, Mail Server and other defaultsettings). I've read and understand why this is bad practice, but I'm struggling with the best solution. From searching, I think the solution would be a module which is loaded when required but I'd like to keep a couple of the scripts separate rather than place in one giant module. Advice appreciated.



  • #16419

    Points: 1,811
    Helping HandTeam Member
    Rank: Community Hero

    Module-level variables are indeed a good way to go, but that's only part of the solution (at least, for me).

    I believe that each function in the module should define parameters for all of those things. The parameter can default to the module-level variable. That enables you to "globally" set those preferences, but still provides all input to the functions by means of parameters, which is much easier for someone else to decode, if they need to.

    If a script is going to be entirely self-contained, then there's no reason not to simply define these variables within it. Or, have it load a module that defines module-level variables. Keep in mind that any exported module-level variables will seem to be global so long as the module is loaded.

  • #16467

    Points: -19
    Rank: Member

    You might be also interested in this module which makes logging awesomely easy.

    Uses Reflection to intercept text output headed for the PowerShell console or ISE. Lines of output are sent to any number of subscriber objects for the purpose of producing complete log files of script output (including date/timestamps) without the need for extra code by the script author.

The topic ‘How to replace global variables?’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort