Work with Environment Variables using Windows PowerShell – Part I

Question: Hey dotnet-helpers, I wanted to see the values of all the Environment variables in my servers/PC, How do I do this in PowerShell?

Dotnet-helpers Reply :

Windows environment variables provide information about the Windows operating system. Separated into the system and user-level scopes, default environment variables can be read and modified, and new environment variables can be also added.

PowerShell can access and manage environment variables in any of the supported operating system platforms. The PowerShell environment provider simplifies this process by making it easy to view and change the environment variables.

We access environment variables using the built-in variable called $env followed by a colon and the name of the environment variable. The $env variable can be used to access all user context environment variables.

Display all the Environmental Variables

Example 1: Get Environment Variables using dir/gci/cd

Syntax : dir env: OR gci env: OR ls env: OR cd env:

You can get the complete list of environment variables using the below cmdlets which will list out all the environment variables as shown below.

Example 2: Get Environment Variables using Get-Childitem

You can get the complete list of environment variables using the Get-Childitem cmdlet. The following command list all the local environment variables.

Get-Childitem -Path Env:* | Sort-Object Name

Dispay the specific Environment Variable

Syntax : $Env:<variable-name>

In the above syntax, the dollar sign ($) indicates a variable, and the drive name (Env:) indicates an environment variable followed by the variable name (windir).

Example 1: Get Specific Environment variable using $ENV

This script will find temporary files.

$ENV:TEMP

Example 2: Get Specific Environment variable using Get-Childitem

Instead of listing all the environment variables, you can also get the value of a specific environment variable by passing the specified variable name.

Get-Childitem Env:computername

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.