1

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I like your thinking @mjolinor . I'm not a hashtable guru, and am hoping to find a mechanism like having a provider masquerade as a namespace, or use a hashtable, because both are easy for non powershell afficionados to use. I am generating the PoSH in Python, so I can convert the dot-sourced file to hash of hashes and try it out for effect latter.
One advantage of using a hashtable in this scenario is that you don't have to explicitly scope it when adding elements to a hashtable in a parent scope.
Something else you might want to consider is using here-strings in the called scripts to populate your values and constants, and then use convertfrom-stringdata to convert them to hash tables when it's time to pull those values back into the main script.
Unfortunately the convertfrom-stringdata cmdlet is designed only for strings, while I have actually got hashtables and collections in my data. (It is a cool commandlet I never know about :-) The fact I will have hashtable of hashes in the implementation is not a barrier to the end user though. Unless I see any other solutions posted before the weekend, I am going to give this answer to you, I just need to document the solution that I settle on.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.