Windows show env variables

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 может помочь сократить время, необходимое для набора команд в командной строке или, если вы часто пишете скрипты для собственных задач, сделать их более читаемыми. В большинстве случаев обычные пользователи добавляют записи в системную переменную среды 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

Прежде чем приступать, учтите: изменение системных переменных среды по умолчанию может привести к проблемам в работе системы, не удаляйте уже имеющиеся переменные среды. Возможно, имеет смысл создать точку восстановления системы, если вы не уверены в своих действиях.

  1. Чтобы открыть переменные среды Windows вы можете использовать поиск в панели задач (начните вводить «Переменных» и откройте пункт «Изменение системных переменных среды») или нажать клавиши Win+R на клавиатуре, ввести sysdm.cpl и нажать Enter.
    Открыть изменение переменных среды в Windows

  2. На вкладке «Дополнительно» нажмите кнопку «Переменные среды…»
    Переменные среды в параметрах системы Windows

  3. В разделе «Переменные среды пользователя» (если требуется изменение только для текущего пользователя) или «Системные переменные» выберите переменную, которую нужно изменить и нажмите «Изменить» (обычно требуется именно это), либо, если необходимо создать новую переменную — нажмите кнопку «Создать». В моем примере — добавляем свои пути в системную переменную Path (выбираем эту переменную и нажимаем «Изменить»).
    Создание и изменение переменных среды Windows

  4. Для добавления нового значения (пути) в системную переменную в следующем окне можно нажать кнопку «Создать», либо просто дважды кликнуть по первой пустой строке, затем — ввести нужный путь к папке, содержащей нужные нам исполняемые файлы.
    Изменение переменно PATH

  5. Также вы можете использовать кнопку «Изменить текст», в этом случае окно изменения системной переменной откроется в ином виде: имя переменной, а ниже — её значение. В случае указания путей значение будет представлять собой все пути, хранящиеся в переменной, разделенные знаком «точка с запятой».
    Изменение имени и значения системной переменной среды

  6. При создании новой переменной среды окно будет тем же, что и в 5-м шаге: необходимо будет указать имя системной переменной в верхнем поле, а её значение — в нижнем.

После создания или изменения переменной среды и сохранения сделанных настроек, переменная или обновленные значения сразу становятся доступны для текущего пользователя или в системе в целом в зависимости от того, какие именно переменные редактировались или создавались. Также есть методы добавления переменных среды в командной строке или PowerShell, подробнее в статье: Как добавить путь в переменную среды PATH

Переменные окружения (среды) в 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 - переменные окружения процесса

In computer programming, variables are the storage locations for values, and the values themselves can be anything. It could be a number, a filename, or some other piece of data. In a similar fashion, there are things called Environment Variables in your Operating System.

Environment Variables are global variables that store values linked to the current working environment and can be utilized by the operating system and other applications to retrieve necessary operating system information. Environment Variables are also known as env variables. Environment Variables are available in Windows, Mac, and Linux.

Table of Contents

  • List of Environment variables in Windows Environment 
    • List environment variables using Command Line
    • List environment variables using Powershell
    • Using reg query command in Command Prompt
  • List of Environment variables in Linux Environment  
  • List of Environment variables in macOS Environment  
  • Conclusion:

They are created as pairs consisting of a number and a value, and both the operating system and the application are able to access those values. The General Format of environment value looks like this:

Variable1 = C:\xyz
Variable2 = 6
variable2 ='val1:val2'
variable4 = val1;val2
...

These types of environment variables can be viewed, created, edited, and deleted. Environment Variable in general helps applications to know which directory to install installable files, and where to find user and system settings.

Some of the environment variables are PATH, USER, HOME, UID, SHELL, TERM, EDITOR, etc.PATHTEXT, OS, TEMP,SYstemRoot.PATH is a popular Environment variable that is available in Windows, Mac, and Linux.

If you want to know what environment variables are used in various OS then I will guide you on this.

List of Environment variables in Windows Environment 

There are actually two types of environment variables in Windows. They are :

1. Local/User Environment Variable: User Variables store information that is unique to the logged-in user and are only relevant during the current session. They have located under the «HKEY_CURRENT_USER/Environment» path in the Registry

2. System Environment Variable: Because they are set uniformly across all of your computer’s users, system variables don’t contain any user-specific data. All user accounts are affected by these global variables.They are located under «HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/ControlSession /ManagerEnvironment» path in Registry

There is various way to list environment variables in windows. Let’s discuss some of them.

List environment variables using Command Line

In the command prompt type :

SET

and press Enter.

set-environment-variable

fig. List all windows environment variable

Some of the most common environment variables:

Environment Variables Description
%APPDATA% AppData contains data and settings of various installed programs on your PC.
%COMPUTERNAME% The unique identifier is given to your computer
%HOMEPATH% HomePath describes the path for the user’s personal files. It contains user files like downloads, Desktop, Documents, Videos, Picture, Contacts, and many more.
%PATH% The PATH variable provides the directories on the machine where executable programs can be found.
%CD% Returns the current directory string.
%DATE% The most recent date, formatted according to the Date command.
%LOGONSEVER% This function brings back the name of the domain controller that was responsible for validating the current logon session.
%NUMBER_OF_PROCESSORS% This number indicates how many processors are currently installed on the computer.
%OS% This function returns the name of the operating system.
%PROMPT% The directory in which the operating system is stored is returned by this function.
%WINDIR% The directory in which the operating system is stored is returned by this function.
%USERNAME% This function gets you the name of the user who is logged in at the moment.
%RANDOM% It returns a random decimal number between 0 and 32767. 

If you have a large number of system and user variables in environment variables then SET displays all at a time. But if you want one page and then one line at a time then try this:

SET | more

set-pipe-more

If you want to save this variable for a future look then you can save it in a text file with the following command.

SET > any_name.txt

fig. output.txt contains an environment variable path

Here, I have used output.txt as the file name, and this file gets saved under C:\User\Dell path and contain output.txt look like this:

output-environmentvariable

If you want help and wants to know more about set cmdlet then type the below command in command prompt for help:

set /?

Note: All commands used here are case insensitive. So, Get-ChildItem Env: is equivalent to get-childitem env:

List environment variables using Powershell

Get-ChildItem (GCI) is a useful cmdlet that is used to get items and, if the item is a container, it will get child items that are available inside the container.

You can simply type below one line to get all environment variables.

Get-ChildItem Env:

or Simply

gci env:

powershell-environmentvariable

As you can see, some lines of the output are truncated. If you want to get the full output without any truncation, use the cmdlet below.

gci Env: | Format-Table -Wrap -AutoSize

or

Get-ChildItem Env: | Format-Table -Wrap -AutoSize

The gci env: cmdlet retrieves all environment variables, which are then passed through the pipeline(|) to Format-Table and displayed in a table. The AutoSize option adjusts column widths to avoid truncation.-Wrap Displays text that exceeds the column width in the new line without truncation.

Below, we can see that no lines in the output are truncated, as they were previously.

gci-cmdlet-without-truncation

Using reg query command in Command Prompt

If you just want System variables then type below in the command prompt

reg query «HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment»

If you just want User variables then type below in the command prompt.

reg query HKEY_CURRENT_USER\Environment

List of Environment variables in Linux Environment  

You can use the below cmdlet in Linux for getting environment variables. I am testing in ubuntu and it must work in other distributions of Linux.

printenv

ubuntu-machine

In Linux, you can simply use the below command for displaying the list of environment variables.

env

It is not possible to view all bash variables when using the env command since it will only show a list of environment variables that have been exported.

List of Environment variables in macOS Environment  

For macOS, we can use printenv for displaying all environment variables.

printenv

Conclusion:

In this approach, we may get a list of all the environment variables in major operating systems such as Windows, Linux, and Mac.

You can view environment variables in the Command Prompt by using the `set` command, which lists all environment variables in the current session. Here’s how to do it:

set

What Are Environment Variables?

Environment variables are dynamic values that the operating system uses to determine how to behave in different circumstances. They serve as a list of key-value pairs that can be used by various applications and scripts running on your computer.

There are two main types of environment variables:

  • User Variables: These are specific to the user account currently logged into the system. They can be tailored to individual user preferences and settings.

  • System Variables: These are global variables accessible to all users on the machine. They define system-wide configurations, such as the path where executable files are located.

Understanding environment variables is crucial for effectively managing software applications and system configurations, as they dictate various settings for the way programs operate.

Check Environment Variables in Cmd: A Quick Tutorial

Check Environment Variables in Cmd: A Quick Tutorial

Why You Might Want to View Environment Variables

Knowing how to view environment variables can be beneficial for several reasons:

  • Modifying System Paths: You might want to add or modify paths for executable files, allowing for quicker access to commands and scripts.

  • Configuring Software Applications: Some applications rely on environment variables for configurations, such as setting database connection strings or API keys.

By viewing environment variables, you can troubleshoot issues, optimize your workflows, and better understand how your system operates.

cmd Echo Environment Variable: Quick Start Guide

cmd Echo Environment Variable: Quick Start Guide

How to Check Environment Variables in Windows CMD

Using the `set` Command

The `set` command is one of the simplest ways to view environment variables within the Windows Command Prompt. When executed without any parameters, the command displays a complete list of all environment variables in your current session.

Syntax:

set

When you run this command, you’ll receive an output that looks something like this:

PATH=C:\Program Files\Java\jdk-11.0.11\bin;C:\Windows\system32;...
USERPROFILE=C:\Users\YourUsername

Each line shows a single environment variable and its current value.

Displaying a Specific Environment Variable

If you’re interested in viewing the value of a specific environment variable, you can use the `echo` command. This is particularly useful for checking the value of common variables like `PATH`.

Syntax:

echo %VARIABLE_NAME%

For example, to check the `PATH` variable, you would execute:

echo %PATH%

The output will display the directories listed in your `PATH`, enabling you to confirm whether the necessary directories are included for executable files.

How to Open Environment Variables from Cmd Easily

How to Open Environment Variables from Cmd Easily

Show Environment Variables CMD: A Detailed Breakdown

Listing All Environment Variables

If you’d like to scroll through the environment variables one page at a time, you can use the `more` command in conjunction with `set`. This technique helps you avoid overwhelming amounts of output in your Command Prompt window.

Code Snippet:

set | more

This command lists all environment variables but pauses for you to read each page, allowing for easier navigation through the output.

Viewing System vs. User Variables

Understanding the difference between user and system variables is essential when managing your environment. To see this distinction, you can use the `systeminfo` command.

Code Snippet:

systeminfo | findstr /i "environment"

The output from this command will include a summary of environmental variables and will help you differentiate between those set for the user and those available to the system. This is valuable when troubleshooting variable-related issues.

Mastering Variables in Cmd: A Quick Reference Guide

Mastering Variables in Cmd: A Quick Reference Guide

Show Environment Variables Windows CMD: GUI vs. Command Line

Accessing Environment Variables via GUI

Windows provides a graphical interface to access environment variables via the System Properties. You can navigate to Control Panel > System > Advanced system settings > Environment Variables. This view provides an organized way to edit or view variables.

While this method is user-friendly, it lacks the speed and efficiency of using the command line, especially for those who are experienced with CMD commands.

Advantages of Using CMD to Show Environment Variables

Using CMD offers distinct advantages:

  • Speed and Efficiency: Commands can quickly display or modify environment variables without navigating through multiple GUI windows.

  • Automation Capabilities: Commands can be scripted for batch processing, making repetitive tasks simpler and faster.

Delete Files Cmd: A Quick Guide to File Removal

Delete Files Cmd: A Quick Guide to File Removal

Troubleshooting Common Issues

Environment Variables Not Showing

If you find that expected environment variables are not showing in your CMD session, there could be several reasons. First, ensure that you are running the Command Prompt with sufficient permissions. Running as an administrator may be necessary for system-level variables.

Additionally, if you see unexpected output, it may be due to incorrect syntax or mistyping the variable name. Always check the correct casing and spelling of the variables.

Modifying Environment Variables through CMD

For those interested in making permanent changes to environment variables, the `setx` command can be employed. This command enables you to create or modify variables for future sessions.

Syntax:

setx VARIABLE_NAME "value"

For example, if you want to set a new user variable related to HTML files, you could run:

setx HTML_PATH "C:\html_files"

Keep in mind that changes made using `setx` will only apply to new Command Prompt sessions.

Mastering Cmd Set Variable: Quick Guide for Beginners

Mastering Cmd Set Variable: Quick Guide for Beginners

Understanding Environment Variables in Batch Scripting

Using Environment Variables in Scripts

Environment variables can significantly enhance the functionality of batch scripts. By incorporating them, you can customize script behavior based on user settings or system configurations.

For instance, you can use environment variables to specify a user directory dynamically:

@echo off
echo User directory is: %USERPROFILE%

This line will output the current user’s profile directory when the script is executed, allowing scripts to adapt to different users without hardcoding values.

Exploring Cmd System Variables: A Quick Guide

Exploring Cmd System Variables: A Quick Guide

Conclusion

Understanding how to view environment variables cmd is a fundamental skill for anyone looking to leverage the full capabilities of Windows. Whether you’re troubleshooting issues, fine-tuning your system’s performance, or scripting automation tasks, being able to confidently access and manage these variables is invaluable. With the commands and techniques discussed here, you are well on your way to mastering Windows Command Prompt and enhancing your workflow.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Программа для восстановления dll файлов windows 10
  • Как объединить две подсети windows
  • Как получить рут права на windows 10
  • Office 16 click to run extensibility component как удалить windows 11
  • Ping по mac адресу windows