fbpx Interact with PowerShell’s Global Environment | Windows PowerShell, Windows Server | HostingUltraso.com
24/7/365 Support

Interact with PowerShell’s Global Environment

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.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say