How to replace global variables?

This topic contains 2 replies, has 3 voices, and was last updated by  nohandle 3 years, 2 months ago.

  • Author
    Posts
  • #16407

    Will
    Participant

    Hi,
    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.

    thanks

    Will

  • #16419

    Don Jones
    Keymaster

    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

    nohandle
    Member

    You might be also interested in this module https://github.com/dlwyatt/PowerShellLoggingModule which makes logging awesomely easy. [blockquote]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.[/blockquote]

You must be logged in to reply to this topic.