I'm working on a PowerShell module script (`*.psm1`) where I define some global variables and an `OrderedDictionary`. In another script file (`*.ps1`), I try to access these variables, but I'm running into an issue where the script fails when attempting to reference the `OrderedDictionary`. Essentially, while I can access a global variable without problems, the loop that processes the `OrderedDictionary` throws an error saying it cannot index into a null array. Is there a proper way to export and access an `OrderedDictionary` from another script?
3 Answers
When you import a `.psm1` file, only the exported items such as functions and variables are available in your current scope. If you want to access your `OrderedDictionary` in another script, you need to explicitly export it by adding `Export-ModuleMember -Variable ForeColour` at the end of your module. Doing this should allow you to access it seamlessly from your other script.
You're right about needing to export variables explicitly if you're not including a `.psd1` file. It's a good practice to use `.psd1` for managing exported variables and functions if your module gets larger. It helps keep things organized and clear.
Thank you very much, will look into the *.psd1 powershell file. I have so much to learn.
In addition to the previous comments, just a heads up that setting your variables to global scope isn't usually recommended. It's often a sign that your script might have scope issues. You could consider using a smaller scope like Script or Private for better encapsulation.
Advice well noted, I have set -Scope to Script, and -Visibility to Private. All works fine.
Thank you so much, worked a treat!