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