How to Set Environment Variables in PowerShell

Environment variables store key information on your system that programs can use to influence their behavior. For example, the AWS CLI uses the AWS_REGION variable to determine the region for API requests.

This guide will cover:
– Listing all environment variables
– Retrieving the value of a specific environment variable
– Setting or updating environment variables

1. List All Environment Variables

To view all environment variables and their current values, use the Get-ChildItem cmdlet with the Env: drive. Alternatively, you can use its shorter alias gci:

# List all environment variables
Get-ChildItem Env:

# Alt cmdlet
gci Env:
PowerShell gci env:

Both commands will display a list of environment variables along with their values.

2. Get the Value of a Specific Environment Variable

To return the value of a specific environment variable, such as AWS_DEFAULT_REGION, you can use one of these methods:

# Get the value of the aws_default_region environment variable
gci Env:\AWS_DEFAULT_REGION

# Do the same but alt (easier) syntax
$env:AWS_DEFAULT_REGION
PowerShell Show Environment Variable Value

Both commands will output the value of the AWS_DEFAULT_REGION variable if it is set.

3. Set or Update an Environment Variable

To set or update an environment variable, assign a new value to it using the $env: syntax:

# Set the AWS Default Region Environment Variable
$env:AWS_DEFAULT_REGION="eu-west-2"
PowerShell Set Environment Variable

Important Notes:
– This change applies only to the current PowerShell session.
– To make the change permanent, you need to update the system or user environment variables in the Windows environment settings or use registry editing scripts.

For example, setting a permanent environment variable using PowerShell might involve modifying the registry:

[System.Environment]::SetEnvironmentVariable("AWS_DEFAULT_REGION", "eu-west-2", "User")  

This approach ensures that the variable is available in future sessions.


Recent Posts
Categories
Tags

Always On Availability Groups (AAG) (4) AWS (4) AWS Redshift (6) Database Admin (72) Database Backups & Recovery (14) Database Mirroring (2) Error Messages (5) Failover Cluster Instances (FCI) (1) Git Commands (6) Importing & Exporting Data (2) Linked Servers (3) Linux Administration (2) Logging & Monitoring (1) Microsoft Patching (2) MySQL (4) Postgres (6) PowerShell Scripts (2) SQL Certificates & Encryption (3) SQL Server Agent (5) SQL Server CDC (2) SQL Server Data Types (2) SQL Server Management Studio (SSMS) (17) SQL Server Networking (3) SQL Server on Linux (1) SQL Server Patching (2) SQL Server Performance Tuning (6) SQL Server Processes (SPIDs) (7) SQL Server Replication (2) SQL Server Scripts (13) SQL Server Security (4) SQL Server Storage (10) Windows Admin (20) Windows Authentication (2) Windows Automation (1) Windows Events (2) Windows Firewall (4) Windows Subsystem for Linux (WSL) (18)