Finding windows environment variables

Windows Environment Variables Tutorial

What’s Environment Variables

Environment variables are system-wide global variables. They are config parameters and is used by processes. For example, apps need to know the path of your Windows kernal, path of your home dir, paths to search for shell programs, etc.

Windows environment variable names are not case sensitive

View Environment Variables

Press ❖ Window key, then type “environment”

Type in shell c:\Windows\System32\SystemPropertiesAdvanced.exe to launch the GUI app directly.

Windows 10 SystemPropertiesAdvanced 2021-02-04

Sample Values of Environment Variable

Here’s example of env var values as it exists on my system.

One of the most important environment variable is PATH . Here’s a sample value of path (with line break added for easy reading):

value of the environment variable PATH

Types of Environment Variable

There are 3 types of environment variable:

Process Per session. It is temporary. It exist only for the current session in cmd.exe or PowerShell. After you exit the shell, the variables you created are gone. When a shell starts, it gets environment variable from the Windows Registry. User Permanent, stored in Windows Registry. Per user. Each user may have different values.
Examples: home folder HOMEPATH , temp dir ( TEMP and or TMP ).
In Registry, they are at: HKEY_CURRENT_USER\Environment . Machine Permanent, stored in Windows Registry. Per machine. Each machine may have different values.
Examples:

  • OS kernal path ( WINDIR )
  • processor info ( PROCESSOR_ARCHITECTURE , NUMBER_OF_PROCESSORS , etc)
  • application paths ( PATH )
  • executable file name extensions ( PATHEXT )
  • OS type ( OS )
  • current user name ( USERNAME )

In Registry, they are at:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
[see Microsoft Windows Registry Tutorial]

Process environment variable is also known as Local Environment Variable.

User environment variable and Machine environment variable are together also known as System Environment Variable.

Note that you can set any new env vars in any category. Programs have access to all your env vars, but which ones are meaningful to the program is up to the program.

Изучаем переменные среды в Windows 10

Переменные среды Windows

Получить информацию о существующих переменных можно в свойствах системы. Для этого кликаем по ярлыку Компьютера на рабочем столе правой кнопкой мыши и выбираем соответствующий пункт.

Переходим в «Дополнительные параметры».

В открывшемся окне с вкладкой «Дополнительно» нажимаем кнопку, указанную на скриншоте ниже.

Здесь мы видим два блока. Первый содержит пользовательские переменные, а второй системные.

Если требуется просмотреть весь перечень, запускаем «Командную строку» от имени администратора и выполняем команду (вводим и нажимаем ENTER).

На рабочем столе появится файл с названием «set.txt», в котором будут указаны все переменные окружения, имеющиеся в системе.

Все их можно использовать в консоли или скриптах для запуска программ или поиска объектов, заключив имя в знаки процента. Например, в команде выше вместо пути

Примечание: регистр при написании переменных не важен. Path=path=PATH

Переменные PATH и PATHEXT

Если с обычными переменными все понятно (одна ссылка – одно значение), то эти две стоят особняком. При детальном рассмотрении видно, что они ссылаются сразу на несколько объектов. Давайте разберемся, как это работает.

Читайте также:  Статья как установить linux

«PATH» позволяет запускать исполняемые файлы и скрипты, «лежащие» в определенных каталогах, без указания их точного местоположения. Например, если ввести в «Командную строку»

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

    Поместить необходимый файл в одну из указанных директорий. Полный список можно получить, выделив переменную и нажав «Изменить».


Создать свою папку в любом месте и прописать путь к ней. Для этого (после создания директории на диске) жмем «Создать», вводим адрес и ОК.

%SYSTEMROOT% определяет путь до папки «Windows» независимо от буквы диска.

Затем нажимаем ОК в окнах «Переменные среды» и «Свойства системы».

Для применения настроек, возможно, придется перезапустить «Проводник». Сделать это быстро можно так:

Открываем «Командную строку» и пишем команду

taskkill /F /IM explorer.exe

Все папки и «Панель задач» исчезнут. Далее снова запускаем «Проводник».

Еще один момент: если вы работали с «Командной строкой», ее также следует перезапустить, то есть консоль не будет «знать», что настройки изменились. Это же касается и фреймворков, в которых вы отлаживаете свой код. Также можно перезагрузить компьютер или выйти и снова зайти в систему.

Теперь все файлы, помещенные в «C:\Script» можно будет открывать (запускать), введя только их название.

«PATHEXT», в свою очередь, дает возможность не указывать даже расширение файла, если оно прописано в ее значениях.

Принцип работы следующий: система перебирает расширения по очереди, пока не будет найден соответствующий объект, причем делает это в директориях, указанных в «PATH».

Создание переменных среды

Создаются переменные просто:

    Нажимаем кнопку «Создать». Сделать это можно как в пользовательском разделе, так и в системном.


Вводим имя, например, «desktop». Обратите внимание на то, чтобы такое название еще не было использовано (просмотрите списки).


В поле «Значение» указываем путь до папки «Рабочий стол».


Нажимаем ОК. Повторяем это действие во всех открытых окнах (см. выше).

  • Перезапускаем «Проводник» и консоль или целиком систему.
  • Готово, новая переменная создана, увидеть ее можно в соответствующем списке.

    Для примера переделаем команду, которую мы использовали для получения списка (самая первая в статье). Теперь нам вместо

    потребуется ввести только

    Заключение

    Использование переменных окружения позволяет значительно сэкономить время при написании скриптов или взаимодействии с системной консолью. Еще одним плюсом является оптимизация создаваемого кода. Имейте в виду, что созданные вами переменные отсутствуют на других компьютерах, и сценарии (скрипты, приложения) с их использованием работать не будут, поэтому перед тем, как передавать файлы другому пользователю, необходимо уведомить его об этом и предложить создать соответствующий элемент в своей системе.

    Share Environment Vars between WSL and Windows

    December 22nd, 2017

    Hey WSL users—we have more features to share with you! Our latest Windows Insider build lets you share environment variables between WSL and Windows. Starting with Build 17063, let’s look at how you can leverage the new “WSLENV” to enhance environmental variable interop between Win32/WSL.

    Summary

    For the pros who’ve already heard about WSLENV and just want to know how it works, see below for a quick synopsis:

    • WSLENV is a colon-delimited list of environment variables that should be included when launching WSL processes from Win32 or Win32 processes from WSL
    • Each variable can be suffixed with a slash followed by flags to specify how it is translated
    • The value is a path that should be translated between WSL paths and Win32 paths
    • The value is a list of paths. In WSL, it is a colon-delimited list. In Win32, it is a semicolon-delimited list
    • The value should only be included when invoking WSL from Win32
    • The value should only be included when invoking Win32 from WSL
    • You can set WSLENV in .bashrc or in the custom Windows environment for your user
    Читайте также:  Cirrus logic high definition audio driver windows 10

    A sample of how a WSLENV could possibly look:

    What are Environment Variables?

    Environment variables are a way to store configurable values across your entire system—all your programs have access to these. On Windows, you can find your environmental variables by going to “Edit environment variables for your account” in the Control Panel. It will show a window like the one below:

    Notice the wide range of values in the example above—lists of directories, software versions, locations where temporary files are permitted to be stored, and more. Who sets these values? You can, newly installed software on your system can, or Windows has set some of them.

    An example of a well-known environmental variable is PATH. Much like the name implies, PATH contains a list of directories (paths) separated by a semi-colon which point to the locations of numerous executables. Here’s a common example of how PATH is used:

    I’m about to invoke Node from the command line. When I enter this command, cmd reads the contents of PATH, searching for a directory that contains the executable “node.exe”. If it finds it, it stop the search immediately and invokes the executable it found. The image above has PATH printed to the console—and you’ll notice that the last entry in PATH points to a directory which does in fact contain Node.

    WSL and environment variables — before Insider 17063

    Referencing environment variables from *both *Windows and WSL introduces interop issues. Prior to 17063, the only Windows environment variable that WSL had access to was PATH (so you could launch Win32 executables from under WSL). But there was no way to set an environment variable in WSL, invoke a Win32 process, and expect for that variable to be fed through to the process.

    Given these limitations, you couldn’t pass an environment var in WSL to a Win32 process without jumping though convoluted hoops. Since passing environment vars to processes is a common practice and we received plenty of feedback concerning how this was a pain point for our users, we wanted to make this a better experience.

    WSL and environment variables — after Insider 17063

    We’re introducing a special environmental var named WSLENV to assist in the flow between WSL and Win32. WSLENV is shared; it exists in both environments. A user sets the value of WSLENV to a concatenation of several other already-defined environment vars , each suffixed with a slash followed by flags to specify how the value should be translated. An example definition could be something like this:

    There are four flags you can use to influence how they’re translated. Let’s walk through each:

    This flag indicates that a path should be translated between WSL paths and Win32 paths. Notice in the example below how we set the var in WSL, add it to WSLENV with the ‘/p’ flag, and then read the variable from cmd.exe and the path translates accordingly.

    This flag indicates the value is a list of paths. In WSL, it is a colon-delimited list. In Win32, it is a semicolon-delimited list. See in the example below how PATHLIST is appropriately converted to a semi-colon separated list.

    This flag indicates the value should only be included when invoking WSL from Win32. In the example below, we set FORWSL from cmd and it will show up in WSL.

    Notice how it does not convert the path automatically—we need to specify the /p flag to do this. We can combine flags and do just that:

    This flag indicates the value should only be included when invoking Win32 from WSL.

    Passing vars with a script

    If you’re writing a bash script and want to pass environment variables to some process that you will be invoking, you can do this:

    Читайте также:  Рейтинг популярности линукс дистрибутивов

    One important thing to call out here is that I am appending the environment variable I want to pass to the process to WSLENV. We recommend this so you don’t wipe out the other vars previously set for WSLENV.

    An Example with Go

    For example, say you want to set up a dev environment with Go in WSL. With the WSLENV var, we can configure it to share GOPATH between WSL and Win32. If you’ve never used Go before, if your project directory is outside of the root directory where Go is installed then you need to set GOPATH. Let’s walk through an end-to-end example.

    1. Install Go on Windows & WSL

    First, we need to install Go on both platforms. To install on Windows, grab Go and select Windows as your platform. Click through and complete the installation. Next, install Go in WSL. We need to issue this command from WSL:

    2. Grab VSCode

    Next, we’ll want to install VSCode in Windows. If you don’t already have VSCode, you can get it from here.

    3. Set up the project

    Next, we need to set up our Go project. The project needs to be under the Windows file system (I’ll just make mine on my Desktop). Issue the following commands in PowerShell:

    Open the newly created hello.go file with VSCode or your favorite text editor and add this text to it:

    4. Set Environment Variables

    Now we need to set our GOPATH to point to this project, and then add GOPATH to WSLENV. From PowerShell:

    5. Success

    That’s all you need to do. If you open the project file in VSCode, it will prompt you about missing package–click yes to install these. After they complete their installation, you will have full VSCode integration (intellisense, linting, etc). On the WSL side, now if you navigate to your project directory (it will be under /mnt/c/…) and try to “go build”, it will run successfully and output a Linux binary that you can run in WSL. Debugging from VSCode will produce a Windows executable that you can also run.

    Conclusion

    We hope using the new WSLENV environment variable will help with interoperating between WSL and Win32. Grab Insider Build **17063 **to try it out. We would love to get feedback on this feature. Is it too clunky? does it work the way you’d hoped? Leave a comment below and let us know.

    What happens if I set an environment var in WSLENV from Win32 which is already defined in WSL?

    The definition in WSL (via .profile or other) will override the value defined in WSLENV when accessed via WSL.

    What about the other way around (variable defined in Win32, then defined and shared from WSL?)

    The WSLENV definition will override the value previously defined in Win32 (the opposite of the above question).

    What happens if I concatenate WSLENV to the end of my PATH environment var?

    It will not concatenate anything—WSLENV gets chopped off.

    Do the changes I make to WSLENV from WSL persist after I close WSL?

    No, you’ll need to modify the appropriate config file (.profile, .bash_rc, etc) and set WSLENV to whatever you’d like.

    Can I set WSLENV to an actual filesystem path or does it have to be set to an existing environment var?

    You can set the value to whatever you’d like. Although, if you were to set a filesystem path, no translation occurs. That’s why we recommend setting WSLENV to the environment variable containing the path and you’ll get the path-translation flags for free.

    Craig Wilhite

    Program Manager, WSL, Containers, and Hyper-V

  • Оцените статью