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!
Переменные окружения (среды) в Windows содержат различную информацию о настройках системы и среды пользователя. Различают переменные окружения пользователя, системы и процессов.
Самый простой способ просмотреть содержимое переменных окружения в Windows – открыть свойства системы (sysdm.cpl) -> Дополнительно -> Переменные среды. Как вы видите, в открывшемся есть две секции: в верхней содержатся переменные окружения пользователя, в нижнем – системные.
Кроме того, переменные среды хранятся в реестре системы. Пользовательские переменные хранятся в разделе HKEY_CURRENT_USER\Environment. Системные – в HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.
Вывести значения всех переменных окружения можно в командной строке Windows. Команда простая:
Set
Команда выведет список переменных среды и их значения.
В PowerShell для вывод всех переменных окружения можно использовать команду:
ls env:
Если нужно вывести значение только одной переменной, нужно воспользоваться командой echo, причем имя переменной нужно заключить в знаки процентов. Например,
Echo %systemroot%
Чтобы сохранить все переменные среды и их значения в текстовый файл, воспользуйтесь командой:
set > c:\tmp\env_var.txt
Переменные окружения конкретного процесса можно получить с помощью бесплатной утилиты Process Explorer (от Sysinternals). Достаточно открыть свойства процесса и перейти на вкладку Environment.
Настройка переменных среды Windows может помочь сократить время, необходимое для набора команд в командной строке или, если вы часто пишете скрипты для собственных задач, сделать их более читаемыми. В большинстве случаев обычные пользователи добавляют записи в системную переменную среды PATH, хотя бывают и другие задачи.
В этой пошаговой инструкции базовая информация о том, как открыть переменные среды Windows 11 и Windows 10, создать или отредактировать их.
Что такое переменные среды
Переменные среды в Windows — записи о расположении системных папок, свойствах системы и другие, которые доступны для любой программы или скрипта.
Одна из наиболее часто используемых переменных среды — PATH, указывающая на папки, в которых выполняется поиск файлов, вызываемых в командной строке, терминале Windows, файле bat или из других источников. В качестве примера её назначения:
- Если вы откроете командную строку (или диалоговое окно «Выполнить»), введёте regedit и нажмете Enter — вы сможете запустить редактор реестра, не указывая полный путь к файлу regedit.exe, поскольку путь C:\Windows добавлен в переменную среды Path.
- Если же тем же образом в командной строке написать имя программы, путь к которой не добавлен в Path (chrome.exe, adb.exe, pip и другие), вы получите сообщение «Не является внутренней или внешней командой, исполняемой программой или пакетным файлом».
Если предположить, что вы часто используете команды adb.exe (например, для установки приложений Android в Windows 11), pip install (для установки пакетов Python) или любые другие то для того, чтобы не писать каждый раз полный путь к этим файлам, имеет смысл добавить эти пути в переменные среды.
Также вы можете добавлять и иные переменные среды (не обязательно содержащие пути), а в дальнейшем получать и использовать их значения в сценариях BAT (командной строки) или PowerShell. Пример получения и отображения значения системной переменной PATH для обоих случаев:
echo %PATH% echo $Env:PATH
Получить список всех переменных среды в командной строке и PowerShell соответственно можно следующими командами:
set ls env:
Редактирование переменных среды Windows 11/10
Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.
- Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter.
- На вкладке «Дополнительно» нажмите кнопку «Переменные среды…»
- В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»).
- Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы.
- Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой».
- При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.
После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались. Также есть методы добавления переменных среды в командной строке или PowerShell, подробнее в статье: Как добавить путь в переменную среды PATH
To open environment variables from the Command Prompt (cmd), you can use the `set` command to view all environment variables or `echo` command for a specific variable, such as the `PATH` variable.
echo %PATH%
Understanding Environment Variables
What are Environment Variables?
Environment variables are dynamic values that the operating system and applications use to determine various settings and paths. They provide a way to configure the environment in which programs run and can significantly affect how applications interact with the system. Common environment variables include:
- PATH: Indicates the directories that the shell searches for executable files.
- TEMP: Specifies the directory where temporary files are stored, often used by applications for a short duration.
Understanding these variables is crucial for troubleshooting applications and configuring system settings.
Why Use Environment Variables?
Using environment variables allows for a flexible and dynamic way to configure your system. They can define user preferences, control the behavior of programs, or provide crucial paths needed for certain tasks. For instance, if you are developing software, you may need to adjust the PATH variable to include the directory of your programming tools.
Check Environment Variables in Cmd: A Quick Tutorial
Accessing Environment Variables through CMD
Opening Command Prompt
To begin working with environment variables through CMD, you first need to open the Command Prompt. Here’s how to do it:
- Press Win + R to open the Run dialog.
- Type cmd and hit Enter or click OK.
- Alternatively, you can search for Command Prompt in the Start menu.
Once the Command Prompt opens, you are ready to interact with your environment variables.
Viewing Current Environment Variables
Understanding the current environment variables set in your system can be very useful. You can use the following commands to view them:
Using the `SET` Command
The `SET` command displays all environment variables and their values. To see a complete list, simply type:
set
Running this command will output all the environment variables currently available in your session.
Using the `ECHO` Command
If you’re interested in viewing a specific environment variable, the `ECHO` command is a great way to do that. For example, to view the PATH variable, enter:
echo %PATH%
This command will print out the value of the PATH environment variable on your screen, helping you to understand which directories are included for executable files.
Getting a Specific Environment Variable
If you want to access another specific variable, such as TEMP, you can use the `ECHO` command in the same fashion:
echo %TEMP%
This will output the path of the temporary files directory. Understanding these specific variable values can help with application performance and configuration.
View Environment Variables Cmd with Ease
Opening Environment Variables Graphically
Accessing Through System Properties
While using CMD is efficient, sometimes a graphical interface can be more intuitive, especially for users unfamiliar with command-line operations. To access the environment variables graphically:
- Right-click on This PC or My Computer on your desktop or in the File Explorer.
- Select Properties.
- Click on Advanced system settings on the left sidebar.
- Under the System Properties window, click the Environment Variables button.
This interface provides a user-friendly way to view and edit user and system environment variables.
cmd Echo Environment Variable: Quick Start Guide
Using the `SET` Command
If you need to temporarily set an environment variable that will only last for the current session, you can use the `SET` command. For example, to set a variable named MY_VAR, you would type:
set MY_VAR=HelloWorld
This command creates a new environment variable called MY_VAR with the value HelloWorld for the duration of this CMD session. Keep in mind that once you close the CMD window, the variable will be lost.
Using the `SETX` Command for Permanent Changes
For those looking to make permanent changes that persist even after closing the CMD window, `SETX` is the command to use. This command allows you to set environment variables that remain available across system reboots. For instance, to create or modify the MY_VAR variable permanently, you would execute:
setx MY_VAR "HelloWorld"
Note that when using `SETX`, you won’t see immediate output in the current session. Instead, it will take effect in new CMD instances or after a restart.
How to Open Services from Cmd in a Flash
Best Practices when Working with Environment Variables
Safety Precautions
Adjusting environment variables can significantly impact system behavior, so it’s wise to back up existing variables before making changes. To do this, simply copy the current variable values before modifying them, as this can prevent unwanted errors or issues later.
Common Mistakes to Avoid
One common pitfall when using CMD for environment variable management is forgetting the percentage signs around variable names when using the `ECHO` command. For example, `echo PATH` will not work as expected; it should be `echo %PATH%`. Additionally, ensure that any values with spaces are enclosed in quotes when using `SETX`.
How to Open Control Panel from Cmd: Quick Steps Explained
Conclusion
Through this guide, you have learned how to open environment variables from cmd and manage them effectively. Whether you’re viewing, modifying, or understanding these dynamic values, mastering CMD commands can enhance your productivity and system configuration skills.
Feel free to practice these commands and explore different environment variables to see how they impact your Windows experience! For ongoing tips and tricks related to CMD, don’t hesitate to follow our resources for more insights.
How to Open Another Drive in Cmd Easily
Additional Resources
Recommended Reading
For more in-depth learning, consider checking out additional documentation on CMD commands and environment variables available through Microsoft’s official resources or other programming community websites.
Community and Support
Engaging with forums and communities dedicated to CMD users can provide assistance and additional insight. Join discussions on platforms like Stack Overflow or dedicated programming forums to connect with like-minded individuals.
How to Open PowerShell from Cmd in Simple Steps
FAQs
What if I can’t find my environment variables?
If you’re unable to see your environment variables, ensure you’re using an elevated CMD (Run as Administrator) for system-level variables. You can also check the graphical interface via System Properties to confirm their existence.
How do I restore default environment variables?
If you’ve made changes that you want to revert, you can either set the environment variables back to their original values manually or, if applicable, use system restore points to revert your system settings.
This article explains how to display the contents of an environment variable from the command prompt in Windows using the echo command.
- An environment variable is a named object that stores data used by applications or the operating system. To display the value of an environment variable, you need to enclose it in percent signs (%). For example, echo %PATH%.
- You can also use wildcards (*) to display all environment variables that match a certain pattern. For example, echo %P*. To display all environment variables and their values, you can use the set command without any arguments. For example, set.
- You can also use the command prompt to set, modify, and delete environment variables using the setx command. You need to specify whether the variable is a user variable or a system variable using the /m switch. For example, setx MYVAR Hello /m.
If you want to check the value of an environment variable in Windows, you can use the command prompt to display it. An environment variable is a named object that stores data used by applications or the operating system. For example, the PATH variable contains a list of directories where executable files are located.
In this article, you will learn how to display the contents of an environment variable from the command prompt in Windows using some simple commands and examples. You will also learn how to set, modify, and delete environment variables using the command prompt.
Table of Contents
- What is the Command Prompt?
- How to Display the Contents of an Environment Variable from the Command Prompt
- How to Set, Modify, and Delete Environment Variables from the Command Prompt
- Frequently Asked Questions (FAQs)
- Question: How do I display the contents of multiple environment variables at once?
- Question: How do I display the contents of an environment variable in a file?
- Question: How do I display the contents of an environment variable in another program?
- Summary
What is the Command Prompt?
The command prompt is a text-based interface that allows you to interact with your computer by typing commands. You can use the command prompt to perform various tasks, such as launching programs, managing files and folders, troubleshooting issues, and more.
To open the command prompt in Windows, you can use one of the following methods:
- Press Windows + R keys to open the Run dialog box, type cmd, and press Enter.
- Press Windows + X keys to open the Power User menu, and select Command Prompt or Command Prompt (Admin).
- Type cmd in the Windows search box, and click on Command Prompt from the results.
To display the contents of an environment variable from the command prompt, you need to use the echo command. The echo command prints a message or a value to the screen. To display the value of an environment variable, you need to enclose it in percent signs (%). For example, if you want to see the value of the PATH variable, you can type:
echo %PATH%
This will show something like this:
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd
You can also use wildcards (*) to display all environment variables that match a certain pattern. For example, if you want to see all environment variables that start with P, you can type:
echo %P*
This will show something like this:
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PATH=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=3a09
PROGRAMDATA=C:\ProgramData
PROGRAMFILES=C:\Program Files
PROGRAMFILES(X86)=C:\Program Files (x86)
PROMPT=$P$G
PSMODULEPATH=C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
PUBLIC=C:\Users\Public
If you want to see all environment variables and their values, you can use the set command without any arguments. For example, if you type:
set
This will show something like this:
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
COMPUTERNAME=DESKTOP-1234567
ComSpec=C:\Windows\system32\cmd.exe
HOMEDRIVE=C:
HOMEPATH=\Users\User
LOCALAPPDATA=C:\Users\User\AppData\Local
LOGONSERVER=\\DESKTOP-1234567
NUMBER_OF_PROCESSORS=4
OS=Windows_NT
...
How to Set, Modify, and Delete Environment Variables from the Command Prompt
You can also use the command prompt to set, modify, and delete environment variables. However, you need to be aware of two types of environment variables: user variables and system variables.
User variables are specific to each user account and are stored in the user profile. System variables are global to all users and are stored in the registry.
To set, modify, or delete a user variable from the command prompt, you need to use the setx command. The setx command creates or modifies a user or system environment variable permanently. The syntax of the setx command is:
setx variable value [/m]
Where variable is the name of the environment variable, value is the value to assign to it, and /m is an optional switch that specifies that the variable should be set in the system environment instead of the user environment.
For example, if you want to create a user variable named MYVAR with the value Hello, you can type:
setx MYVAR Hello
This will create the MYVAR variable in the user environment and display a message like this:
SUCCESS: Specified value was saved.
To verify that the variable was created, you can type:
echo %MYVAR%
This will show something like this:
Hello
Note that the setx command does not affect the current command prompt session. You need to open a new command prompt window to see the changes.
If you want to modify the value of an existing user variable, you can use the same setx command with a different value. For example, if you want to change the value of MYVAR to World, you can type:
setx MYVAR World
This will overwrite the previous value of MYVAR and display a message like this:
SUCCESS: Specified value was saved.
To verify that the variable was modified, you can type:
echo %MYVAR%
This will show something like this:
World
If you want to delete a user variable, you can use the setx command with an empty value. For example, if you want to delete MYVAR, you can type:
setx MYVAR ""
This will remove the MYVAR variable from the user environment and display a message like this:
SUCCESS: Specified value was deleted.
To verify that the variable was deleted, you can type:
echo %MYVAR%
This will show something like this:
%MYVAR%
To set, modify, or delete a system variable from the command prompt, you need to use the setx command with the /m switch. For example, if you want to create a system variable named SYSVAR with the value Test, you can type:
setx SYSVAR Test /m
This will create the SYSVAR variable in the system environment and display a message like this:
SUCCESS: Specified value was saved.
To verify that the variable was created, you can type:
echo %SYSVAR%
This will show something like this:
Test
Note that you need administrative privileges to modify or delete system variables. You can run the command prompt as an administrator by right-clicking on it and selecting Run as administrator.
Frequently Asked Questions (FAQs)
Question: How do I display the contents of multiple environment variables at once?
Answer: You can use the echo command with multiple variables separated by spaces. For example, if you want to display the values of PATH, PATHEXT, and PROCESSOR_ARCHITECTURE variables, you can type:
echo %PATH% %PATHEXT% %PROCESSOR_ARCHITECTURE%
This will show something like this:
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Git\cmd .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC AMD64
Question: How do I display the contents of an environment variable in a file?
Answer: You can use the redirection operator (>) to send the output of a command to a file. For example, if you want to save the value of PATH variable in a file named path.txt, you can type:
echo %PATH% > path.txt
This will create a file named path.txt in your current directory with the value of PATH variable as its content.
Question: How do I display the contents of an environment variable in another program?
Answer: You can use the substitution operator (&) to run multiple commands in one line. For example, if you want to display the value of PATH variable in Notepad, you can type:
echo %PATH% & notepad
This will show the value of PATH variable in the command prompt and then open Notepad.
Summary
In this article, you learned how to display the contents of an environment variable from the command prompt in Windows using some simple commands and examples. You also learned how to set, modify, and delete environment variables using the command prompt.
Disclaimer: This article is for informational purposes only and does not constitute professional advice. The author and publisher are not responsible for any errors or omissions, or for any consequences arising from the use of the information in this article. Always consult a qualified professional before making any decisions based on the information in this article.