Breaking the Powershell namespace limit of global,

2019-08-03 05:24发布

问题:

How can I create namespaces or "providers" in a script without writing any C#, or using anything not already inside the Windows Box? - Alternately put, can I reference variables in a script by the name of the script I dot-sourced them from? I want to avoid clashes when dot sourcing a generated PoSH script. Set-Variable cmdlet does not give any clues as to where to look next, is there perhaps a cmdlet to create providers with all the framework done for you? At the moment I am using a "global" (ick) variable-list to track all values I define, basically I am trying to build a library, and in this case, the library supplies data values/constants.

回答1:

You can check $myinvocation within the called script to find the script name.

It sounds like you could implement a kind of pseudo-namespace in the main script by making your variable list a hash table of hash tables, and then each value would be referenced in the main script as $vars.scriptname.scriptvariable.