Environment Variables
Context and History
Environment variables are an essential mechanism in modern operating systems, allowing the storage of configuration information and the transmission of parameters to processes. They were introduced in the early Unix systems and were adopted by Windows with the arrival of Windows NT.
Why Use Environment Variables
-
Global Configuration
- Paths to executables (
PATH), temporary directory (TEMP/TMP), language and regional format (LANG).
- Paths to executables (
-
Isolation and Portability
- Scripts and applications can read their parameters without hardcoding absolute paths.
-
Propagation to Child Processes
- Any variable defined in a parent process is inherited by its children.
Types and Scope
| Scope | Persistent? | Accessible from | Example Variable |
|---|---|---|---|
| Process | No | Current process | $env:MYVAR = "session" |
| User | Yes | Any user process (new session) | Set-Variable USER via GUI or PowerShell |
| Machine | Yes | Any user and any process (new session) | Set-Variable MACHINE |
- Session (process): temporary modification, disappears upon closing.
- User: stored in the registry under
HKCU:\Environment. - System (Machine): stored in the registry under
HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.
Management via Graphical Interface
Search for "Environment" in Windows settings.
The Env Provider in PowerShell
PowerShell exposes environment variables as a "PSDrive" called Env:.
Listing and Reading
# List all environment variables
Get-ChildItem Env:
# Read a specific variable
Get-Item Env:PATH
# or
$env:PATH
setx Utility
The Windows binary setx allows quick writing:
# Sets for the user (default)
setx LOG_LEVEL "DEBUG"
# Sets for the machine (with /M, requires Admin)
setx NODE_ENV "production" /M
Note:
setxdoes not modify the current session — it saves for future sessions.
Best Practices
- Name in UPPERCASE and use
_to separate words. - Limit the size of
PATH: too long can break some programs. - Document in a script or README any persistent modification.
- Backup the state before major changes (registry export).
- Test in VM: validate scripts on your virtual machines before deployment.
Key Takeaways
- Environment variables are a fundamental mechanism for transmitting parameters to processes.
- They have three scopes: Session, User, Machine.
- PowerShell and
setxoffer powerful ways to read, set, and delete these variables. - Always test on VM and document your changes!