Hey everyone! I'm in the process of reorganizing my PowerShell profile by splitting it into multiple files. Each of these files contains functions and variables that I want to use in the global scope. I tried creating a couple of functions, like `get-mod` and `load-mod`, to load these scripts, but I've run into an issue. When I use `. $module` to execute the script, it runs inside the scope of `load-mod`, which means the functions I define in those scripts aren't accessible from the command line. I'm aware that using `Import-Module` is a common approach, but I'm curious if there's a way to run these scripts so they execute in the global scope instead. Thanks!
3 Answers
To make your variables accessible globally, you can use `$Global:MyVariable`. However, for functions, it's best to stick to modules for better organization. Your current setup executes in the function's runtime context, which is why you're facing this issue.
Yeah, exactly! I don't want to keep prefixing everything with `$Global:`. I was hoping for something like a wrapper function to manage scope better.
Avoid cluttering your profile with too many functions. Instead, expose the functions in your modules located in the `psmodulepath`, so they get loaded only when you call them by name.
Instead of loading scripts this way, you might want to put your functions into a proper module. This not only avoids scope issues but also keeps everything organized.
Just out of curiosity, do you have a specific reason to avoid modules? I found that running `. (get-mod profile.git)` worked fine for me when I needed to load it.
Totally agree! Using a module allows you to scope your variables and functions appropriately and keeps your profile cleaner.
Can you explain why it creates a messy environment? I'm trying to access the functions and variables directly from the CLI, so wouldn't using global variables suffice?