Windows print env variable

What is an environment variable in Windows? An environment variable is a dynamic “object” containing an editable value which may be used by one or more software programs in Windows.

In this note i am showing how to list environment variables and display their values from the Windows command-line prompt and from the PowerShell.

Cool Tip: Add a directory to Windows %PATH% environment variable! Read More →

The environment variables in Windows can be printed using the Windows command-line prompt (CMD) or using the PowerShell.

Windows Command-Line Prompt (CMD)

List all Windows environment variables and their values:

C:\> set

“Echo” the contents of a particular environment variable:

C:\> echo %ENVIRONMENT_VARIABLE%

Windows PowerShell

Print all Windows environment variables (names and values):

PS C:\> gci env:* | sort-object name

Show the contents of a particular environment variable:

PS C:\> echo $env:ENVIRONMENT_VARIABLE

Cool Tip: Set environment variables in Windows! Read More →

Was it useful? Share this post with the world!

Environment variables are not often seen directly when using Windows. However there are cases, especially when using the command line, that setting and updating environment variables is a necessity. In this series we talk about the various approaches we can take to set them. In this article we look at how to interface with environment variables using the Command Prompt and Windows PowerShell. We also note where in the registry the environment variables are set, if you needed to access them in such a fashion.

Print environment variables

You can use environment variables in the values of other environment variables. It is then helpful to be able to see what environment variables are set already. This is how you do it:

Command Prompt

List all environment variables

Command Prompt — C:\>

Output

1
2
3
4
5
6
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\user\AppData\Roaming
.
.
.
windir=C:\Windows

Print a particular environment variable:

Command Prompt — C:\>

Output

Windows PowerShell

List all environment variables

Windows PowerShell — PS C:\>

Output

1
2
3
4
5
6
7
8
Name                           Value
----                           -----
ALLUSERSPROFILE                C:\ProgramData
APPDATA                        C:\Users\user\AppData\Roaming
.
.
.
windir                         C:\Windows

Print a particular environment variable:

Windows PowerShell — PS C:\>

Output

Set Environment Variables

To set persistent environment variables at the command line, we will use setx.exe. It became part of Windows as of Vista/Windows Server 2008. Prior to that, it was part of the Windows Resource Kit. If you need the Windows Resource Kit, see Resources at the bottom of the page.

setx.exe does not set the environment variable in the current command prompt, but it will be available in subsequent command prompts.

User Variables

Command Prompt — C:\>

1
setx EC2_CERT "%USERPROFILE%\aws\cert.pem"

Open a new command prompt.

Command Prompt — C:\>

Output

1
C:\Users\user\aws\cert.pem

System Variables

To edit the system variables, you’ll need an administrative command prompt. See HowTo: Open an Administrator Command Prompt in Windows to see how.

Command Prompt — C:\>

1
setx EC2_HOME "%APPDATA%\aws\ec2-api-tools" /M

Warning This method is recommended for experienced users only.

The location of the user variables in the registry is: HKEY_CURRENT_USER\Environment. The location of the system variables in the registry is: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

When setting environment variables through the registry, they will not recognized immediately. One option is to log out and back in again. However, we can avoid logging out if we send a WM_SETTINGCHANGE message, which is just another line when doing this programatically, however if doing this on the command line it is not as straightforward.

One way is to get this message issued is to open the environment variables in the GUI, like we do in HowTo: Set an Environment Variable in Windows — GUI; we do not need to change anything, just open the Environment Variables window where we can see the environment variables, then hit OK.

Another way to get the message issued is to use setx, this allows everything to be done on the command line, however requires setting at least one environment variable with setx.

Printing Environment Variables

With Windows XP, the reg tool allows for accessing the registry from the command line. We can use this to look at the environment variables. This will work the same way in the command prompt or in powershell. This technique will also show the unexpanded environment variables, unlike the approaches shown for the command prompt and for powershell.

First we’ll show the user variables:

Command Prompt — C:\>

1
reg query HKEY_CURRENT_USER\Environment

Output

1
2
3
HKEY_CURRENT_USER\Environment
    TEMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp
    TMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp

We can show a specific environment variable by adding /v then the name, in this case we’ll do TEMP:

Command Prompt — C:\>

1
reg query HKEY_CURRENT_USER\Environment /v TEMP

Output

1
2
HKEY_CURRENT_USER\Environment
    TEMP    REG_EXPAND_SZ    %USERPROFILE%\AppData\Local\Temp

Now we’ll list the system environment variables:

Command Prompt — C:\>

1
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
    ComSpec    REG_EXPAND_SZ    %SystemRoot%\system32\cmd.exe
    FP_NO_HOST_CHECK    REG_SZ    NO
    NUMBER_OF_PROCESSORS    REG_SZ    8
    OS    REG_SZ    Windows_NT
    Path    REG_EXPAND_SZ    C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\
    PATHEXT    REG_SZ    .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
    PROCESSOR_ARCHITECTURE    REG_SZ    AMD64
    PROCESSOR_IDENTIFIER    REG_SZ    Intel64 Family 6 Model 60 Stepping 3, GenuineIntel
    PROCESSOR_LEVEL    REG_SZ    6
    PROCESSOR_REVISION    REG_SZ    3c03
    PSModulePath    REG_EXPAND_SZ    %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files\Intel\
    TEMP    REG_EXPAND_SZ    %SystemRoot%\TEMP
    TMP    REG_EXPAND_SZ    %SystemRoot%\TEMP
    USERNAME    REG_SZ    SYSTEM
    windir    REG_EXPAND_SZ    %SystemRoot%

And same as with the user variables we can query a specific variable.

Command Prompt — C:\>

1
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v PATH

Output

1
2
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
    PATH    REG_EXPAND_SZ    C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\

Unsetting a Variable

When setting environment variables on the command line, setx should be used because then the environment variables will be propagated appropriately. However one notable thing setx doesn’t do is unset environment variables. The reg tool can take care of that, however another setx command should be run afterwards to propagate the environment variables.

The layout for deleting a user variable is: reg delete HKEY_CURRENT_USER\Environment /v variable_name /f. If /f had been left off, we would have been prompted: Delete the registry value EXAMPLE (Yes/No)?. For this example we’ll delete the user variable USER_EXAMPLE:

Command Prompt — C:\>

1
reg delete HKEY_CURRENT_USER\Environment /v USER_EXAMPLE /f

Output

1
The operation completed successfully.

Deleting a system variable requires administrator privileges. See HowTo: Open an Administrator Command Prompt in Windows to see how to do this.

The layout for deleting a system variable is: reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v variable_name /f. For this example we’ll delete the system variable SYSTEM_EXAMPLE:

Command Prompt — C:\>

1
reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v SYSTEM_EXAMPLE /f

If this was run as a normal user you’ll get:

Output

1
ERROR: Access is denied.

But run in an administrator shell will give us:

Output

1
The operation completed successfully.

Finally we’ll have to run a setx command to propagate the environment variables. If there were other variables to set, we could just do that now. However if we were just interested in unsetting variables, we will need to have one variable left behind. In this case we’ll set a user variable named throwaway with a value of trash

Command Prompt — C:\>

Output

1
SUCCESS: Specified value was saved.

Resources

  • Windows XP Service Pack 2 Support Tools
  • Windows Server 2003 Resource Kit Tools
  • Reg — Edit Registry | Windows CMD | SS64.com
  • Reg — Microsoft TechNet
  • Registry Value Types (Windows) — Microsoft Windows Dev Center
  • How to propagate environment variables to the system — Microsoft Support
  • WM_SETTINGCHANGE message (Windows) — Microsoft Windows Dev Center
  • Environment Variables (Windows) — Microsoft Windows Dev Center

Windows Server 2003 Resource Kit Tools will also work with Windows XP and Windows XP SP1; use Windows XP Service Pack 2 Support Tools with Windows XP SP2. Neither download is supported on 64-bit version.

Parts in this series

  • HowTo: Set an Environment Variable in Windows

  • HowTo: Set an Environment Variable in Windows — GUI

  • HowTo: Set an Environment Variable in Windows — Command Line and Registry

The `echo` command in CMD is used to display messages or the value of environment variables in the command prompt.

echo %PATH%

Understanding CMD and Environment Variables

What is CMD?

CMD, short for Command Prompt, is a command-line interpreter in Windows operating systems. It serves as a powerful tool that allows users to execute commands, run scripts, and manage files directly through textual commands. Originating from earlier systems like MS-DOS, CMD remains an essential utility for system administrators, developers, and tech enthusiasts. Its functionality extends from basic operations, such as file management, to advanced scripting capabilities.

What are Environment Variables?

Environment variables are dynamic values that the operating system uses to determine various settings and configurations. Each variable carries specific information about the environment in which your commands run. For instance, the `PATH` variable stores a list of directories that the operating system searches when you run a command. This allows users to execute programs without needing to specify their complete paths.

Some commonly used environment variables include:

  • `PATH`: Directories where the system looks for executable files.
  • `TEMP`: The path designated for temporary files.
  • `USERPROFILE`: The path to the current user’s profile directory.

Understanding and managing environment variables is crucial for effective system operation and command line functionality.

Check Environment Variables in Cmd: A Quick Tutorial

Check Environment Variables in Cmd: A Quick Tutorial

The `echo` Command in CMD

What is the `echo` Command?

The `echo` command is a built-in command in CMD that displays messages and environment variable values to the console. It is a common tool used in scripts and batch files for providing information to users or signaling the outcome of operations.

Syntax of the `echo` Command

The simple syntax for the `echo` command is:

echo [message]

You can provide several options, such as:

  • `echo on`: You can enable command echoing.
  • `echo off`: You can disable command echoing and suppress command display.

View Environment Variables Cmd with Ease

View Environment Variables Cmd with Ease

Using `echo` to Display Environment Variables

Accessing Environment Variables in CMD

Before using the CMD `echo` command for environment variables, you may want to list all available ones. To view all environment variables, simply type:

set

This will present a comprehensive list of all environment variables defined in your session.

Using `echo` to Display a Specific Environment Variable

To display a specific environment variable using the `echo` command, you can reference it with `%` signs surrounding the variable name. For example, to show the value of the `USERPROFILE` variable, you would use:

echo %USERPROFILE%

This command outputs the current user’s profile directory path, showcasing how `echo` effectively pulls and displays environmental settings.

Practical Applications of `echo` with Environment Variables

The versatility of the `echo` command allows it to be used for various practical applications. It can be especially useful in script debugging or showing runtime variable values. For instance, consider the following script snippet that creates a custom variable and displays its value:

@echo off
set MY_VAR=%USERPROFILE%\Documents
echo The document folder is located at: %MY_VAR%

In this example, `MY_VAR` becomes an alias for the documents folder path specific to the user. The script succinctly outputs the directory location, enhancing clarity and understanding of variable utilization.

How to Open Environment Variables from Cmd Easily

How to Open Environment Variables from Cmd Easily

Advanced Use Cases of `echo` with Environment Variables

Combining `echo` with Other Commands

The `echo` command can also be effectively combined with other commands to form powerful utility scripts. For instance, consider piping output to files or combining it with the `set` command to verify values:

set MY_ENV_VAR=Hello
echo %MY_ENV_VAR%

In this instance, `MY_ENV_VAR` is assigned the value «Hello,» and `echo` confirms the assignment, facilitating script checks.

Environment Variables in Batch Files

When creating batch files, the power of `echo` becomes even more pronounced. By using `echo` in conjunction with environment variables, you can enlighten users about system settings effortlessly. Below is a simple example of how to leverage these concepts in a batch file:

@echo off
echo Current PATH is: %PATH%
echo User Profile is: %USERPROFILE%

This script provides useful information to the user, making it easier to understand the current system configuration without having to manually check each variable.

Mastering Cmd Set Variable: Quick Guide for Beginners

Mastering Cmd Set Variable: Quick Guide for Beginners

Troubleshooting Common Issues with `echo` and Environment Variables

Common Errors and Their Solutions

While working with `echo` and environment variables, you may encounter several common issues, such as:

  • Undefined Variables: If a variable returns as empty, ensure that it is defined in the current session.
  • Incorrect Syntax: Always double-check your syntax, particularly the use of `%` when accessing variable values.

Best Practices for Using `echo` with Environment Variables

To effectively manage environment variables when using `echo`, consider these best practices:

  • Clarity in Naming: Use intuitive names for user-defined variables to reduce confusion.
  • Avoid Conflicts: Be cautious of defining variables that may override existing system variables. Naming conventions or prefixes can help mitigate conflicts.
  • Documentation: Comment on critical parts of scripts to explain what variables represent, ensuring ease of understanding for others reviewing your code.

Exploring Cmd System Variables: A Quick Guide

Exploring Cmd System Variables: A Quick Guide

Conclusion

The combination of the `cmd echo environment variable` provides a robust toolset for both simple and advanced command line operations. Mastering these commands not only enhances your productivity but also deepens your understanding of how your operating system functions. By leveraging `echo` effectively with environment variables, you can greatly improve your ability to manage and utilize system configurations in Windows CMD.

Cmd Echo Current Directory: A Simple Guide

Cmd Echo Current Directory: A Simple Guide

Additional Resources

For further reading, consider checking the official Microsoft documentation on CMD commands, environment variables, and batch scripting techniques. Utilizing forums and community sources can also provide additional insights and tools that support CMD learning and usage.

Переменные окружения (среды) в Windows содержат различную информацию о настройках системы и среды пользователя. Различают переменные окружения пользователя, системы и процессов.

Самый простой способ просмотреть содержимое переменных окружения в Windows – открыть свойства системы (sysdm.cpl) -> Дополнительно -> Переменные среды. Как вы видите, в открывшемся есть две секции: в верхней содержатся переменные окружения пользователя, в нижнем – системные.

переменные окружения Windows

Кроме того, переменные среды хранятся в реестре системы. Пользовательские переменные хранятся в разделе HKEY_CURRENT_USER\Environment. Системные – в HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.

HKEY_CURRENT_USER\Environment

Вывести значения всех переменных окружения можно в командной строке Windows. Команда простая:

Set

команда Set

Команда выведет список переменных среды и их значения.

В PowerShell для вывод всех переменных окружения можно использовать команду:

ls env:

Если нужно вывести значение только одной переменной, нужно воспользоваться командой echo, причем имя переменной нужно заключить в знаки процентов. Например,

Echo %systemroot%

Чтобы сохранить все переменные среды и их значения в текстовый файл, воспользуйтесь командой:

set > c:\tmp\env_var.txt

список переменных окружения в текстовом виде

Переменные окружения конкретного процесса можно получить с помощью бесплатной утилиты Process Explorer (от Sysinternals). Достаточно открыть свойства процесса и перейти на вкладку Environment.

Process Explorer - переменные окружения процесса

Understanding and accessing environment variables is fundamental to effectively manage and configure system settings on Windows. Environment variables store essential information, such as system paths, user preferences, and system configurations, which applications and scripts often rely upon. Displaying all these variables can provide valuable insights into the system’s state and can be crucial for troubleshooting or customizing the computing environment. This tutorial provides 2 methods how to print all environment variables on Windows.

Method 1 — CMD

Command Prompt (CMD) provides the SET command to manage environment variables. This command enables to view a comprehensive list of environment variables and their corresponding values.

SET

Output example:

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\User\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
...

Method 2 — PowerShell

PowerShell, a more advanced and versatile command-line interface, offers the gci env: command to access environment variables. This command will present a detailed list of all environment variables, including their names and values.

gci env:

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не меняется атрибут только для чтения windows 10
  • Как отключить новости на панели задач windows 11
  • Windows 7 riva tuner
  • Windows 10 1909 отзывы
  • Windows server 2012 настроить dns сервер на windows