Установить переменную окружения windows cmd

Introduction

Environment variables are key-value pairs a system uses to set up a software environment. The environment variables also play a crucial role in certain installations, such as installing Java on your PC or Raspberry Pi.

In this tutorial, we will cover different ways you can set, list, and unset environment variables in Windows 10.

How to set environment variables in Windows

Prerequisites

  • A system running Windows 10
  • User account with admin privileges
  • Access to the Command Prompt or Windows PowerShell

Check Current Environment Variables

The method for checking current environment variables depends on whether you are using the Command Prompt or Windows PowerShell:

List All Environment Variables

In the Command Prompt, use the following command to list all environment variables:

set
List all environment variables using the Command Prompt

If you are using Windows PowerShell, list all the environment variables with:

Get-ChildItem Env:
List all environment variables using Windows PowerShell

Check A Specific Environment Variable

Both the Command Prompt and PowerShell use the echo command to list specific environment variables.

The Command prompt uses the following syntax:

echo %[variable_name]%
Checking a specific environment variable using the Command Prompt

In Windows PowerShell, use:

echo $Env:[variable_name]
Checking a specific environment variable using Windows PowerShell

Here, [variable_name] is the name of the environment variable you want to check.

Follow the steps to set environment variables using the Windows GUI:

1. Press Windows + R to open the Windows Run prompt.

2. Type in sysdm.cpl and click OK.

Run sysdm.cpl

3. Open the Advanced tab and click on the Environment Variables button in the System Properties window.

Find the Environment Variables button in the Advanced tab

4. The Environment Variables window is divided into two sections. The sections display user-specific and system-wide environment variables. To add a variable, click the New… button under the appropriate section.

Click on the New... button to add a variable

5. Enter the variable name and value in the New User Variable prompt and click OK.

Enter the new variable name and value

Set Environment Variable in Windows via Command Prompt

Use the setx command to set a new user-specific environment variable via the Command Prompt:

setx [variable_name] "[variable_value]"

Where:

  • [variable_name]: The name of the environment variable you want to set.
  • [variable_value]: The value you want to assign to the new environment variable.

For instance:

setx Test_variable "Variable value"
Setting a user-specific environment variable via the Command Prompt

Note: You need to restart the Command Prompt for the changes to take effect.

To add a system-wide environment variable, open the Command Prompt as administrator and use:

setx [variable_name] "[variable_value]" /M
Setting a system environment variable via the Command Prompt

Unset Environment Variables

There are two ways to unset environment variables in Windows:

Unset Environment Variables in Windows via GUI

To unset an environment variable using the GUI, follow the steps in the section on setting environment variables via GUI to reach the Environment Variables window.

In this window:

1. Locate the variable you want to unset in the appropriate section.

2. Click the variable to highlight it.

3. Click the Delete button to unset it.

Unset environment variables in Windows via GUI

Unset Environment Variables in Windows via Registry

When you add an environment variable in Windows, the key-value pair is saved in the registry. The default registry folders for environment variables are:

  • user-specific variables: HKEY_CURRENT_USEREnvironment
  • system-wide variables: HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment

Using the reg command allows you to review and unset environment variables directly in the registry.

Note: The reg command works the same in the Command Prompt and Windows PowerShell.

Use the following command to list all user-specific environment variables:

reg query HKEY_CURRENT_USEREnvironment
Listing all user-specific environment variables in the registry

List all the system environment variables with:

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment"
Listing all system environment variables in the registry

If you want to list a specific variable, use:

reg query HKEY_CURRENT_USEREnvironment /v [variable_name]
Listing a specific user environment variable in the registry

or

reg query "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name]
Listing a specific system environment variable in the registry

Where:

  • /v: Declares the intent to list a specific variable.
  • [variable_name]: The name of the environment variable you want to list.

Use the following command to unset an environment variable in the registry:

reg delete HKEY_CURRENT_USEREnvironment /v [variable_name] /f
Unsetting a user-specific environment variable from the registry

or

reg delete "HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlSession ManagerEnvironment" /v [variable_name] /f
Unsetting a system environment variable from the registry

Note: The /f parameter is used to confirm the reg delete command. Without it, entering the command triggers the Delete the registry value EXAMPLE (Yes/No)? prompt.

Run the setx command again to propagate the environment variables and confirm the changes to the registry.

Note: If you don’t have any other variables to add with the setx command, set a throwaway variable. For example:

setx [variable_name] trash

Conclusion

After following this guide, you should know how to set user-specific and system-wide environment variables in Windows 10.

Looking for this tutorial for a different OS? Check out our guides on How to Set Environment Variables in Linux, How to Set Environment Variables in ZSH, and How to Set Environment Variables in MacOS.

Is it possible to set a environment variable at the system level from a command prompt in Windows 7 (or even XP for that matter). I am running from an elevated command prompt.

When I use the set command (set name=value), the environment variable seems to be only valid for the session of the command prompt.

gary's user avatar

gary

4,2373 gold badges31 silver badges58 bronze badges

asked Sep 27, 2010 at 12:07

Santhosh's user avatar

The XP Support Tools (which can be installed from your XP CD) come with a program called setx.exe:

C:\Program Files\Support Tools>setx /?

SETX: This program is used to set values in the environment
of the machine or currently logged on user using one of three modes.

1) Command Line Mode: setx variable value [-m]
   Optional Switches:
    -m  Set value in the Machine environment. Default is User.

...
For more information and example use: SETX -i

I think Windows 7 actually comes with setx as part of a standard install.

answered Sep 27, 2010 at 14:49

Hugh Allen's user avatar

Hugh AllenHugh Allen

6,5271 gold badge35 silver badges44 bronze badges

5

Simple example for how to set JAVA_HOME with setx.exe in command line:

setx JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

This will set environment variable «JAVA_HOME» for current user. If you want to set a variable for all users, you have to use option «/m» (or -m, prior to Windows 7).

Here is an example:

setx /m JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"

Note: you have to execute this command as Administrator.

Note: Make sure to run the command setx from an command-line Admin window

charlie arehart's user avatar

answered Jun 25, 2012 at 13:30

Mindaugas Jaraminas's user avatar

1

If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.

Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):

SET XYZ=test
SETX XYZ test

answered Jan 13, 2016 at 21:36

Anton F.'s user avatar

Anton F.Anton F.

4664 silver badges8 bronze badges

0

SetX is the command that you’ll need in most of the cases.Though its possible to use REG or REGEDIT

Using registry editing commands you can avoid some of the restrictions of the SetX command — different data types, variables containing = in their name and so on.

@echo off

:: requires admin elevated permissions
::setting system variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v MyVar /D MyVal
::expandable variable
REG ADD "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /T REG_EXPAND_SZ /v MyVar /D MyVal


:: does not require admin permissions
::setting user variable
REG ADD "HKEY_CURRENT_USER\Environment" /v =C: /D "C:\\test"

REG is the pure registry client but its possible also to import the data with REGEDIT though it allows using only hard coded values (or generation of a temp files). The example here is a hybrid file that contains both batch code and registry data (should be saved as .bat — mind that in batch ; are ignored as delimiters while they are used as comments in .reg files):

REGEDIT4

; @ECHO OFF
; CLS
; REGEDIT.EXE /S "%~f0"
; EXIT

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment]
"SystemVariable"="GlobalValue"

[HKEY_CURRENT_USER\Environment]
"UserVariable"="SomeValue"

answered Nov 9, 2020 at 22:52

npocmaka's user avatar

npocmakanpocmaka

55.6k18 gold badges148 silver badges188 bronze badges

For XP, I used a (free/donateware) tool called «RAPIDEE» (Rapid Environment Editor), but SETX is definitely sufficient for Win 7 (I did not know about this before).

answered Nov 8, 2013 at 16:01

FractalSpace's user avatar

FractalSpaceFractalSpace

5,5873 gold badges43 silver badges47 bronze badges

System variables can be set through CMD and registry
For ex. reg query «HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment» /v PATH

All the commonly used CMD codes and system variables are given here: Set Windows system environment variables using CMD.

Open CMD and type Set

You will get all the values of system variable.

Type set java to know the path details of java installed on your window OS.

answered Mar 9, 2017 at 5:04

Himanshu Singh's user avatar

Just in case you would need to delete a variable, you could use SETENV from Vincent Fatica available at http://barnyard.syr.edu/~vefatica.
Not exactly recent (’98) but still working on Windows 7 x64.

answered May 2, 2014 at 21:27

abort's user avatar

abortabort

111 bronze badge

2

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

Before proceeding further into much detail, let me clear one thing. All the changes to the system environment variables on the cmd – command line are valid only for the current window and are not permanently modified.

That is, when the cmd command line window is closed, it will no longer work. There are two ways to permanently modify environment variables: one is to modify the registry (this method is not currently tested), the other is through My computer -> Properties -> Advanced system setting -> Environment variables, to set the system environment variables. we will discuss both the method here i.e. Direct and CMD method.

Set Windows system environment variables

Window Operating system specifies some operating environment or parameters, such as temporary folder location and system folder location. “Path” is a variable which stores some commonly used commands directory path or address. When you run any programs that depend on some regularly used commands these environment variables finds the address of that command and execute the commands easily.  The system variables are set by different programs. Also, if you’re programming in Python environment variables can be used in your programs.

How to check for system environment variables?

When you start the cmd – command line window and call a command. For example, if you type java and press enter then if the system environment has the variable java defined then it will show no error but if the java variable path is not defined then an error is thrown often as “Java is not an internal or external command, operable program or batch file“. This applies to every command.

Java is not an internal or external command, operable program or batch file

If your spelling is not wrong and the computer has that program installed, then the error is caused because your path variable is not set up correctly i.e. you have not given the absolute path of your program. That simply means that the operating system do not know where to find your mention program.

How to Set Windows system environment variables

# Direct Method to Set Windows system environment variables

  1. On your Windows PC go to My computer -> right click anywhere and select Properties -> Advanced system setting -> Environment variables.
  2. Here you will see all the system variables defined on your PC.
  3. Now to set the new variable click on New under System variables and give the name of the variable and value is the path of the variable. for ex: “C:jdkbin” is the value for java home.
  4. Like that you can modify the existing variable by clicking on the edit and changing the values.

system environment variable change directly

#  Using CMD to Set Windows system environment variables

To set the variable using CMD, you have to type different codes. I have mentioned all the possible CMD codes to Modify or Add Windows system environment variables by CMD. Check out the full list of codes below. Open CMD first and begin typing the codes mentioned below. The codes are in BOLD letter.

Also read: How to Clean Your Windows Registry and Speed Up Your PC

  1. To view all available environment variables type SET and press Enter.
  2. To see an environment variable value or path: Type set variable name for example, set java will show you the path or value of the path variable.
  3. To modify the environment variable: type set variable name = variable content for example, to set the java path variable value type set path = C:jdkbin or whatever is your address. 
  4. To set an empty value: If you want to set a variable as empty, type set variable name = 
  5. To add variables to the variable: Type set variable name =%variable name%; variable content. For example set path =% path%; c:programfilesprogram.exe to add c:programfilesprogram.exe to path. %path% is the environment variable. 

cmd set command

Below is the list of commonly used environmental variables and their roles to Set Windows system environment variables.

Also read: Merge video clips into one video file using CMD, without any software

  1. % ALLUSERSPROFILE% – Locates the location of all User Profiles locally .
  2. % APPDATA% – Locally Returns the default case where the application data is stored.
  3. % CD%  – Returns the current directory string locally.
  4. % CMDCMDLINE% –  Returns the exact command line used to start the current Cmd.exe.
  5. % CMDEXTVERSION%  – The system returns the current version of the “command handler extension”.
  6. % COMPUTERNAME%  – The system returns the name of the computer.
  7. % COMSPEC%  – The system returns an exact path to the command line interpreter executable .
  8. % DATE%  – The system returns the current date . Use the same format as date / t command. 
  9. % ERRORLEVEL% –  The system returns the error code of the most recently used command. Often a nonzero value is used to indicate an error.
  10. % HOMEDRIVE% –  The system returns the local workstation drive letter that is connected to the user’s home directory. Based on the setting of the home directory value. The user’s home directory is specified in “Local Users and Groups”.
  11. % HOMEPATH%  –  The system returns the full path to the user’s home directory. Based on the setting of the home directory value. The user’s home directory is specified in “Local Users and Groups”.
  12. % HOMESHARE%  –  The system returns the network path of the user’s shared home directory. Based on the setting of the home directory value. The user’s home directory is specified in “Local Users and Groups”.
  13. % LOGONSEVER%  –  Local Returns the name of the domain controller that validates the current logon session.
  14. % NUMBER_OF_PROCESSORS%  –  The system specifies the number of processors installed on the computer.
  15. % OS%  –  The system returns the name of the operating system. Windows 2000 displays the operating system as Windows_NT.
  16. % PATH% –   The system specifies the search path for the executable file .
  17. % PATHEXT%  –  The system returns a list of file extensions that the operating system considers executable.
  18. % PROCESSOR_ARCHITECTURE%  –  The system returns the processor’s chip architecture.
  19. % PROCESSOR_IDENTFIER%  –  The system returns the processor description.
  20. % PROCESSOR_LEVEL%  –  The system returns the model of the processor installed on the computer.
  21. % PROCESSOR_REVISION% –   The system returns the system variable for the processor revision number.
  22. % PROMPT%  –  Returns the command prompt for the current interpreter . Generated by Cmd.exe.
  23. % RANDOM%  –  The system returns any decimal number between 0 and 32767 . Generated by Cmd.exe.
  24. % SYSTEMDRIVE%  – The system returns a drive that contains the root directory of Windows(that is, the system root).
  25. % SYSTEMROOT% –  The system returns the location of the Windows root directory.
  26. % TEMP% and % TMP%  –  The system and user return the default temporary directory used by the application that is currently available to the logged-on user. Some applications require TEMP, while other applications require TMP.
  27. % TIME%  – The system returns the current time. Use the same format as time /t command. Generated by Cmd.exe.
  28. % USERDOMAIN%  –  Returns the name of the domain containing the user account locally.
  29. % USERNAME%  –  Returns the name of the user who is currently logged in.
  30. % UserProfile% –  Locates the location of the current user’s profile locally.
  31. % WINDIR% –  The system returns the location of the operating system directory.

That’s all n this post. So now you know how to Set Windows system environment variables directly or by using CMD.

Related Articles

Fast and Secure Methods to Convert EML to PDF Format

Overview:  We often get questions from users like” How to convert EML to PDF files in bulk?” If you are such a user, then I would recommend reading the blog…

Laptops under 200

Laptops have become an essential tool for people in all walks of life. Whether you’re a student, a professional, or just someone who wants to stay connected  on the go,…

Beginners Guide for Boosting Home Network Security

With the increasing number of wireless devices in every household, the security of your home network has never been this important. Today, your connection may have multiple mobile phones, laptops,…

How to Convert PST to PDF with Attachments in Bulk

Do you want to convert your PST file to PDF with attachments and looking for a reliable solution to import PST to PDF? Then you do not require to stress…

Can't Play 4k Movies On My Computer

Assuming you’re encountering troubles playing  4k movies on your computer, it tends to be baffling, particularly when you’re anxious to appreciate high-goal content. Different elements can add to this issue,…

How California Residents Can Better Their Online PC Gaming Sessions

Online PC gaming is a passion for millions. It’s a great way to relax after a long day, connect with friends and give yourself a challenge. Thanks to a massive…

Переменная окружения (переменная среды́, англ. environment variable) — текстовая переменная операционной системы, хранящая какую-либо информацию — например, данные о настройках системы или сведения о текущем пользователе.

Работа с переменными¶

В качестве примера можно привести переменную %APPDATA%, которая указывает путь до папки, в которой хранятся настройки некоторых программ текущего пользователя. Обычно это C:\Documents And Settings\Пользователь\Application Data, где Пользователь это изменяемое значение. Для каждой учетной записи используется своё имя пользователя.

Чтобы каждый раз не узнавать имя учетной записи текущего пользователя и не подставлять в путь к папке Application Data соответствующее значение и используется переменная окружения %APPDATA%.

Это позволяет, к примеру, быстро открывать папку Application Data, для этого в меню «Пуск →Найти» или в «Пуск →Выполнить» введите %APPDATA% и нажмите клавишу Enter.

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

echo %PROCESSOR_ARCHITECTURE%

Введенная в командной строке, эта комбинация отобразит архитектуру процессора текущего компьютера. Возможен один из трёх вариантов: x86, IA64, AMD64.

Список переменных¶

Далее приводится список основных переменных, более подробный список приведен в статье Переменная среды Windows.

Основные переменные

Переменная Описание
%APPDATA% Возвращает используемое по умолчанию размещение данных приложений. В Windows XP это C:\Documents and Settings\%UserName%\Application Data. В Windows 7 — C:\Users\%UserName%\AppData\Roaming.
%PROCESSOR_ARCHITECTURE% Архитектура процессора. Возможные варианты: x86, IA64, AMD64.
%USERNAME% Имя текущего пользователя.
%CD% Указывает путь к текущему каталогу. Идентична команде CD без аргументов.
%USERPROFILE% Путь к профилю текущего пользователя.
%WINDIR% Каталог, в котором установлена Windows.
%LOGONSERVER% Имя контроллера домена, использовавшегося для авторизации текущего пользователя.
%HOMEPATH% Возвращает полный путь к основному каталогу пользователя. Задаётся на основании расположения основного каталога. Основной каталог пользователя указывается в оснастке «Локальные пользователи и группы».
%DATE% Возвращает текущую дату. Использует тот же формат, что и команда date /t. Создаётся командой Cmd.exe.
%TIME% Возвращает текущее время. Использует тот же формат, что и команда time /t. Создаётся командой Cmd.exe.
%COMPUTERNAME% Имя компьютера.
%TEMP% и %TMP% Возвращает временные каталоги, по умолчанию используемые приложениями, которые доступны пользователям, выполнившим вход в систему. Некоторые приложения требуют переменную TEMP, другие — переменную TMP. Потенциально TEMP и TMP могут указывать на разные каталоги, но обычно совпадают.
%ROGRAMFILES% Путь к каталогу Program Files.
%PROGRAMFILES(x86)% Путь к каталогу Program Files (x86) в 64-разрядных системах для приложений архитектуры x86.
%PATH% Указывает путь поиска исполняемых файлов.

Изменение переменных¶

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

Предупреждение

Бездумное изменение стандартных значений переменных может привести к необратимым последствиям!

  • Установить обновление kb4534310 для windows 7
  • Установить пароль bios из windows
  • Установить на ноутбук две операционные системы windows
  • Установить драйвера для windows 10 bootcamp
  • Установить панель управления nvidia на windows 10 скачать