Setting Environment Variables in PowerShell: A Practical Guide

Powershell environment variables blog banner

What Are PowerShell Environment Variables? 

PowerShell environment variables are integral to the configuration of the system and the behavior of scripts within the PowerShell environment. They store values that can be used dynamically within scripts and command prompts, such as paths to directories, system configurations, and user-defined data. 

These variables allow for the customization and control of the execution environment, enabling scripts to adapt based on system settings and conditions. By leveraging these variables, system administrators and developers can ensure consistency across different configurations.

Environment variables are used for storing information that various processes can access at runtime. They can be inherent to the system or user-defined for specified tasks. In PowerShell, environment variables can be manipulated to retrieve system information, such as the current working directory or operating system version, and are crucial for automating tasks across different environments. They can also define the behavior of different scripts.

Benefits of Using PowerShell Environment Variables 

Here are the main benefits of using PowerShell environment variables:

  • Automation: Environment variables allow scripts to dynamically adjust based on system settings, reducing the need for hard-coded values and making scripts more maintainable and reusable.
  • Consistency across environments: By using environment variables, scripts can maintain consistent configurations across multiple environments, reducing errors and eliminating the need for custom setups on each machine.
  • Access to system information: Environment variables provide quick access to important system details, such as user paths and OS settings, allowing scripts to adapt based on system properties without complex commands.
  • Security and isolation: Storing sensitive data, like API keys or connection strings, in environment variables instead of scripts helps protect confidential information and supports secure configuration management.
  • Scope and lifetime management: PowerShell allows environment variables to be set at session, user, or machine scope, providing control over the lifespan and visibility of each variable. This flexibility helps prevent clutter and supports more organized environment management.

Related content: Read our guide to Python environment variables

Working with PowerShell Environment Variables 

Here’s an overview of how to use environment variables in PowerShell.

Get Environment Variables with PowerShell

PowerShell provides several ways to retrieve environment variables, allowing users to see all system variables or narrow down based on scope. The most direct method uses the .NET framework, which displays all variables and allows users to specify the scope of the variables—such as user, machine, or process. This flexibility is useful when working with environment variables across different security contexts. 

  1. Here’s how to list all environment variables:
# Using the .NET method to get all environment variables

[System.Environment]::GetEnvironmentVariables()

# Using the PowerShell Environment provider and sorting by name

Get-Item env:* | Sort-Object Name
# Shorthand for the same Environment provider method

gi env:* | Sort Name

# Another option using the drive method

dir env:

The .NET method is particularly valuable if you only need to retrieve user-level variables instead of all variables.

  1. To limit results to user-scope variables, use this command:
# Retrieve only user-scope environment variables

[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)

The environment provider method (e.g., $env:) is shorter and intuitive, especially for quick access to variables. Both methods allow users to understand and manage environment variables across PowerShell sessions, supporting various administrative and development tasks.

View Specific Environment Variables

To retrieve a specific environment variable in PowerShell, use the $env: syntax. This approach is efficient when you know the name of the variable and want to view its value. 

  1. For example, to find the ranker_api_url folder path:
# Retrieve the ranker_api_url folder path
$env:rank_api_url
  1. When you are unsure of the exact name of an environment variable, PowerShell lets you use wildcard patterns with the Get-Item cmdlet, which enables you to search for variables with specific prefixes or substrings. This is helpful in filtering out variables that share similar characteristics, such as those related to paths or specific applications:
# Get all environment variables that start with 'ranking_api_url'
Get-Item env:ranker_api_url*
# Get all environment variables containing 'Path'
Get-Item env:*Path*
  1. Additionally, the .NET method can retrieve a specific variable by its exact name. This command is similar to the full list retrieval, but retrieves only one value, making it ideal for quick checks on specific settings:
# Retrieve a specific environment variable value
[System.Environment]::GetEnvironmentVariable('ranker_api_url')

These methods provide flexibility, enabling you to efficiently retrieve detailed or targeted environment information as needed.

Setting Windows PowerShell Environment Variables

Setting or modifying environment variables in PowerShell is straightforward, allowing for both temporary and permanent changes. 

  1. To add a new directory to the PATH variable for the current session, simply use the $env: syntax. This method is temporary; the modification will reset once the PowerShell session ends:
# Temporarily add a new directory to the PATH environment variable
$env:PATH = $env:PATH + ';C:\bin'
  1. For a more lasting modification—such as updating the PATH environment variable across all sessions—you can use the .NET method with the Machine target. This command permanently updates the system’s environment settings by adding C:\bin to the PATH variable in the machine’s registry:
# Define the path to add

$InstallLocation = "C:\bin"

# Check if path is already in PATH; if not, add it

$persistedPath = [Environment]::GetEnvironmentVariable('Path', [EnvironmentVariableTarget]::Machine) -split ';'

if ($persistedPath -notcontains $InstallLocation) {
$persistedPath += $InstallLocation

[Environment]::SetEnvironmentVariable('Path', $persistedPath -join ';', [EnvironmentVariableTarget]::Machine)
}

In this code, the specified path is checked against the current PATH entries. If it doesn’t already exist, it’s appended, and the variable update is saved in the Machine scope. This ensures that future sessions will retain this path, avoiding the need to reconfigure it manually each time.

Removing Env Variables

Removing environment variables in PowerShell can be done by setting the variable to an empty string, or by deleting it entirely. Setting a variable to an empty string or $null effectively clears its value, while using the Remove-Item cmdlet will fully remove the variable from the session. This is helpful when managing temporary variables or clearing configurations:

# Set the variable to an empty string, effectively clearing it

$env:UserPrincipalName = ''

# Use the .NET method to clear it for the entire machine scope

[Environment]::SetEnvironmentVariable('UserPrincipalName', '', [EnvironmentVariableTarget]::Machine)

# Fully remove the variable using Remove-Item

Remove-Item Env:\UserPrincipalName

Note: Before performing the above operations, check that the environment variable exists. Otherwise you may get an error.

Best Practices for Using PowerShell Environment Variables 

Here are some of the ways that developers and administrators can ensure the most effective use of environment variables in PowerShell.

Persisting Environment Variables

Persisting environment variables involves saving them so that they remain available across different sessions. This can be done by modifying the system’s environment settings through the Windows GUI or using scripts that update configuration files permanently. 

Persisting variables ensures that valuable configurations are not lost between sessions, providing a consistent environment for script execution and system operations. Having persistent environment variables is particularly useful for variables that define consistent environment setups, such as database connection strings or commonly used paths. 

Scope Awareness

Variables can have different scopes – session, process, or system – each influencing where and how they can be accessed. Session variables are temporary, existing only for the life of the PowerShell session. Process variables, meanwhile, impact the current process and its children, while system variables persist across all processes and system reboots.

Being aware of these scopes helps in avoiding unintended behavior and conflicts. When a script requires access to certain variables, it’s important to ensure they are set at the appropriate scope, preventing issues where variables are not accessible or persist longer than intended. 

Conditional Checks Before Setting Variables

Implementing conditional checks before setting environment variables helps avoid overwriting essential system settings. By using conditionals, such as if statements, users can verify if a variable already exists or has a specific value before making changes. This ensures that only necessary updates are applied, protecting existing configurations.

This practice minimizes unintentional errors and preserves existing working configurations. Conditional logic makes scripts more robust and adaptable, as they can respond to different environment states without compromising functionality. 

Cross-Platform Considerations

When using PowerShell environment variables in cross-platform environments, such as Windows, macOS, and Linux, awareness of platform-specific behaviors is essential. Different operating systems might handle environment variables differently, influencing script portability and performance. 

Ensuring compatibility involves testing scripts on all intended platforms to identify discrepancies and adjust code accordingly. Using PowerShell’s cross-platform capabilities, such as PowerShell Core, can help in managing these differences. Developers should be mindful of path separators and case sensitivity, which vary between platforms. 

Use Descriptive Names

Using descriptive names for environment variables improves readability and maintainability of scripts. Clear, meaningful names provide insight into the purpose and function of each variable, making scripts easier to understand and debug. This practice reduces confusion and errors, particularly in collaborative environments where multiple users interact with the same scripts.

Descriptive naming conventions improve the clarity of scripts, allowing faster updates and easier onboarding for new team members. This approach encourages structured, professional script development, enabling better communication and collaboration. 

Related content: Read our guide to testing environment

Tips From the Expert

In my experience, here are tips that can help you better work with PowerShell environment variables:

  1. Use scoped functions for modular variable management: To organize variables, create PowerShell functions that set environment variables within a controlled scope (session, process, or machine). Scoped functions make it easy to modularize and reuse configurations without accidentally affecting other parts of the environment.
  2. Store sensitive information securely: Avoid placing sensitive information directly in scripts; instead, consider storing secrets in secure locations like the Windows Credential Manager or an external vault (e.g., Azure Key Vault or AWS Secrets Manager), and retrieve them in PowerShell as needed.
  3. Implement environment-specific configurations: Use separate configuration files or JSON files with distinct sets of environment variables for development, testing, and production environments. Load the appropriate set based on the environment, simplifying deployment and reducing errors.
  4. Automate environment variable backups: Create scripts to back up environment variables, especially for system scope. Export them to a JSON or CSV file that can be easily imported if needed. This can prevent accidental loss of critical configurations and provides an easy way to restore setups.
  5. Use PowerShell profiles for persistent custom settings: For user-specific, persistent environment variables, configure PowerShell profiles (e.g., $PROFILE.CurrentUserAllHosts). This allows you to customize environment variables across all PowerShell sessions without altering the system or machine scopes.
Ran Cohen photo
Ran Cohen
CTO & Co-Founder, Configu
Before co-founding Configu, Ran was a full stack developer at Testim.io and previously served in an elite cybersecurity unit in the Israeli Defense Forces.

Managing Powershell Environment Variables with Configu

Configu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:

Configu Orchestrator

As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).

The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing confConfigu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:

Configu Cloud

Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.

Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers’ code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.

Learn more about Configu

Related Content

React Environment Variables: Basics, Tutorial, and Best Practices

Working with Python Configuration Files: Tutorial & Best Practices

Jenkins Environment Variables: Practical Guide with Code Examples

Working with Java Environment Variables & 4 Ways to Set Variables

7 Types of Testing Environments and Best Practices for Yours

4 Ways to Set Docker Compose Environment Variables

How to Use Github Actions Environment Variables

Next.js Environment Variables: Built-In, Public, and Private

Node.js Environment Variables: Working with process.env and dotenv

Environment Variables: How to Use Them and 4 Critical Best Practices

Setting Docker Environment Variables: The Ultimate Guide

Leveraging Environment Variables in Python Programming

Try Configu for free
Painless end-to-end configuration management platform
Get Started for Free