Home ยป How to Get Environment Variable in PowerShell

How to Get Environment Variable in PowerShell

To get the environment variable in PowerShell, use the Get-ChildItem cmdlet or [Environment] class.

Method 1: Use the Get-ChildItem cmdlet to Get the Environment Variable by Name

Get-ChildItem -Path Env:\my_variable

This example gets the value of the environment variable by named my_variable.

Method 2: Using the [Environment] Class to Get the Environment Variable by Name

[System.Environment]::GetEnvironmentVariable('my_variable')

This example gets the my_variable environment variable value.

The following examples show how to use each method.

Using the Get-ChildItem cmdlet to Get the Environment Variable By Name

We can use the Get-ChildItem cmdlet on the env: drive to get the environment variable value.

The following PowerShell script gets the environment variable by name.

Get-ChildItem -Path Env:\windir

The output of this example shows the variable name and its value on the terminal.

(base) PS C:\> Get-ChildItem -Path Env:\windir

Name                           Value
----                           -----
windir                         C:\WINDOWS


(base) PS C:\>

To get the value only of an environment variable, use the following syntax.

(Get-ChildItem -Path Env:\windir).Value

The output of the above PowerShell script is :

C:\WINDOWS

Using the [Environment] Class to Get the Environment Variable

The [Environment] class has a static method named GetEnvironmentVariable. We can pass the environment variable and scope to retrieve its value.

The following PowerShell script shows how to do it.

[System.Environment]::GetEnvironmentVariable('MOSQUITTO_DIR')

In this example, we have passed “MOSQUITTO_DIR” as the environment variable name to retrieve its value.

The output of this example is given below.

C:\Program Files\mosquitto

Conclusion

I hope the above article on how to get an environment variable value in PowerShell using the Get-ChildItem cmdlet and [Environment] class is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.