Problem
You want to store information in the PowerShell environment so that other scripts have access to it.
Solution
To make a variable available to the entire PowerShell session, use a $GLOBAL: prefix when you store information in that variable:
## Create the web service cache, if it doesn't already exist
if(not (TestPath Variable:\Lee.Holmes.WebServiceCache))
{
${GLOBAL:Lee.Holmes.WebServiceCache} = @{}
}
If the main purpose of your script is to provide permanent functions and variables for its caller, treat that script as a library and have the caller dotsource the script:
PS >. LibraryDirectory PS >GetDirectorySize Directory size: 53,420 bytes
Discussion
The primary guidance when it comes to storing information in the session’s global environment to avoid it when possible. Scripts that store information in the global scope are prone to breaking other scripts and prone to being broken by other scripts.
It is a common practice in batch file programming, but script parameters and return values usually provide a much cleaner alternative.
If you do find yourself needing to write variables to the global scope, make sure that you create them with a name unique enough to prevent collisions with other scripts, as illustrated in the solution. Good options for naming prefixes are the script name, author’s name, or company name.