Windows 10 Environment Variables: Write environment variables to CMD and PowerShell to view the latest version. Reprint please retain the source.

Author: GC (at)sysin.org, homepage: www.sysin.org

1. Introduction to environment variables

Environment variables are parameters used in an operating system to specify the operating system’s operating environment. An environment variable is an object with a specific name in the operating system that contains information that will be used by one or more applications. The path environment variable in Windows and DOS, when the system is asked to run a program without telling it the full path of the program, the system should look for the program in the path specified in addition to the current directory. Users can set environment variables to better run the process.

Environment variables: Environment variables

  • User variables: User variables
  • System variables: System variables

Environment variables can be divided into user variables and system variables, which have corresponding entries in the registry.

1.1 User Variables

User variables are valid only for the current user.

  • User variable location:HKEY_CURRENT_USER\Environment

1.2 System Variables

System variables are global variables that are valid for all users.

  • System variable location:HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment

1.3 GUI operation environment variables

Graphical Interface (Windows 10) : This computer –> Properties –> Advanced System Settings –> Advanced –> Environment Variables…

You can view, create, edit, and delete environment variables (user and system) directly. The steps are relatively simple and will not be described here.

Note: in text editing mode, add the semicolon in English state on the basis of the original variable, then add the pathname. Do not delete the original system variables, just separate them with a semicolon, and then add the pathname, including a semicolon at the end.

2. Run the CMD command to operate environment variables

2.1 Viewing Environment Variables

View all currently available environment variables: Enter set to view.

To view an environment variable, enter the name of the set variable. For example, to view the value of the path variable, enter set path

Or use the echo % variable name % echo %path%. Note that both user and system variables have path, and the system variable is displayed first.

2.2 Built-in environment Variables

The built-in environment variables are as follows:

%ALLUSERSPROFILE% locally returns the location of all User profiles. The %APPDATA% part returns the default location where the application stores data. %CD% returns the current directory string locally. %CMDCMDLINE% locally returns the exact command line used to launch the current cmd.exe. %CMDEXTVERSION% The system returns the current command Handler Extension version number. %COMPUTERNAME% The name of the computer returned by the system. %COMSPEC% The system returns the exact path to the command line interpreter executable. %DATE% The system returns the current DATE. Use the same format as the date /t command. The command is generated by cmd.exe. For more information about the date command, see Date. %ERRORLEVEL% The system returns the error code of the recently used command. Errors are usually represented by non-zero values. %HOMEDRIVE% The system returns the drive letter of the local workstation connected to the user's home directory. Setting based on the home directory value. The user home directory is specified in Local Users and Groups. %HOMEPATH% The system returns the full path to the user's home directory. Setting based on the home directory value. The user home directory is specified in Local Users and Groups. %HOMESHARE% The network path that the system returns to the user's shared home directory. Setting based on the home directory value. The user home directory is specified in Local Users and Groups. %LOGONSEVER% returns the name of the domain controller that validates the current login session locally. %NUMBER_OF_PROCESSORS% The system specifies the number of processors installed on the computer. %OS% System Returns the name of the operating system. Windows2000Display the operating system as Windows_NT. %PATH% Specifies the search PATH for the executable file. %PATHEXT% The system returns a list of file extensions that the operating system considers executable. %PROCESSOR_ARCHITECTURE% The system returns the chip architecture of the processor. Value: x86, IA64. %PROCESSOR_IDENTFIER% The system returns the processor description. %PROCESSOR_LEVEL% The system returns the model of the processor installed on the computer. %PROCESSOR_REVISION% System variable that the system returns with the processor revision number. %PROMPT% returns the command PROMPT Settings for the current interpreter locally. The command is generated by cmd.exe. %RANDOM% The system returns032767Between any decimal number. The command is generated by cmd.exe. %SYSTEMDRIVE% The system returns the drive containing the Windows XP root directory (that is, the system root directory). %SYSTEMROOT% The system returns to the location of the Windows XP root directory. %TEMP%and%TMP% The system and user return the default temporary directory used by applications available to the currently logged in user. Some applications require TEMP, while others require TMP. %TIME% The system returns the current TIME. Use the same format as the time /t command. The command is generated by cmd.exe. For more information about the time command, see time. The %USERDOMAIN% part returns the name of the domain containing the user account. %USERNAME% returns the name of the currently logged in user locally. The %UserProfile% part returns the location of the current user's profile. %WINDIR% The system returns the location of the operating system directory.Copy the code

2.3 CMD Setting Environment Variables (Temporary)

Add or modify environment variables: set variable name = variable content

TMP =d:\ TMP set TMP =d:\ TMP # set TMP =c:\ TMP set TMP =c:\ TMP #Copy the code

Set to null: set variable name =

set tmp=
Copy the code

Append to variable: set variable name =% variable name %; Variable content

For example, add a path to the path variable

set path=%path%; d:\goCopy the code

To add d:\go to path, run set path=%path%; C :\ TMP, then, when using the set path statement to view, there will be: d:\go; C :\ TMP instead of just c:\ TMP.

Note that this only works in the current command line window. Therefore, environment variables cannot be displayed on the GUI.

2.4 Setting environment variables by writing to the registry

The set command operates on environment variables only for the current session, and does not save changes. Persistent setting of environment variables is implemented by modifying the registry.

The registry location of the environment variable is as follows:

  • The user variable is located: HKEY_CURRENT_USER\Environment

  • SYSTEM variable location: HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\ Controlsession Manager\Environment

Example: Create and append environment variables

The following uses the go environment variable configuration as an example:

Graphical Interface (Windows 10) : This computer –> Properties –> Advanced System Settings –> Advanced –> Environment Variables…

  • User variables:

    • New: GOPATH = %UserProfile%\ GOPATH (e.g. current user is C:\Users\Administrators)
    • PATH variable adds a %GOPATH%\bin
  • System variables:

    • New: GOROOT = C:\go
    • PATH added a %GOROOT%\bin
:: User variable location: 'HKEY_CURRENT_USER\Environment'setUSERregpath=HKEY_CURRENT_USER\Environment :: System variable location: `HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment`setMACHINEregpath=HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment :: User Environment variable :: New reg add"%USERregpath%" /v "GOPATH" /t REG_SZ /d "%UserProfile%\gopath" /f

::PATHAdd :: Query the originalPATHThe value of thefor /F "tokens=3*" %i in ('reg query "%USERregpath%" /v "path" 2^ >nul') do echo %i
for /F "tokens=3*" %i in ('reg query "%MACHINEregpath%" /v "path" 2^ >nul') do echo% I :: in.bat or.cmdIn a batch file, % I should be written as%%i
for /F "tokens=3*" %%i in ('reg query "%USERregpath%" /v "path" 2^ >nul') do echo %%i
for /F "tokens=3*" %%i in ('reg query "%MACHINEregpath%" /v "path" 2^ >nul') do echo %%i

for /F "tokens=3*" %i in ('reg query "%USERregpath%" /v "path" 2^ >nul') do ( set USERpath=%i)
echo USERpath=%USERpath%
reg add "%USERregpath%" /v "Path" /t REG_EXPAND_SZ /d ""%USERpath%"%GOPATH%\bin;" /f :: After testing, giant hard company's different Windows10Version of thePATHVariables are written differently. Some end with a semicolon, and some don't. So the command still needs to be split with a semicolon, and the closing semicolon cancels reg add"%USERregpath%" /v "Path" /t REG_EXPAND_SZ /d "%USERpath%;%GOPATH%\bin" /f :: System environment variable :: New reg add"%MACHINEregpath%" /v "GOROOT" /t REG_SZ /d "C:\go" /f

::PATHadditionalfor /F "tokens=3*" %i in ('reg query "%MACHINEregpath%" /v "path" 2^ >nul') do ( set MACHINEpath=%i)
echo MACHINEpath=%MACHINEpath%
reg add "%MACHINEregpath%" /v "Path" /t REG_EXPAND_SZ /d "%USERpath%;%GOROOT%\bin" /f
Copy the code

Write to batch (save as.bat or.cmd file)

::From: www.sysin.org ::OS Environment: Windows10 (Include Server 2016/2019)

@echoOff :: User variable location: 'HKEY_CURRENT_USER\Environment'setUSERregpath=HKEY_CURRENT_USER\Environment :: System variable location: `HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment`set MACHINEregpath=HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

echo.
echo= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =echoGo Environment variable Settingsecho= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =echo.

set/P EN= Please press Enter to confirm setting start!echo. :: User environment variablesechoCreate the user environment variable GOPATH=%UserProfile%\gopath
reg add "%USERregpath%" /v "GOPATH" /t REG_SZ /d "%UserProfile%\gopath" /f
echo.

echoAdd user environment variablesPATH=%GOPATH%\bin
for /F "tokens=3*" %%i in ('reg query "%USERregpath%" /v "path" 2^ >nul') do ( set USERpath=%%i)
echo USERpath=%USERpath%
reg add "%USERregpath%" /v "Path" /t REG_EXPAND_SZ /d "%USERpath%;%GOPATH%\bin" /f
echo. :: System environment variablesechoGOROOT=C:\go reg add"%MACHINEregpath%" /v "GOROOT" /t REG_SZ /d "C:\go" /f
echo.

echoAdd system environment variablesPATH=%GOROOT%\bin
for /F "tokens=3*" %%i in ('reg query "%MACHINEregpath%" /v "path" 2^ >nul') do ( set MACHINEpath=%%i)
echo MACHINEpath=%MACHINEpath%
reg add "%MACHINEregpath%" /v "Path" /t REG_EXPAND_SZ /d "%USERpath%;%GOROOT%\bin" /f
echo.

color 17
echo************ Go Setting environment variables is complete! * * * * * * * * * * *echo.
echoPlease press any key to exit!pause>nul
Copy the code

3. Powershell operating environment variables

3.1 Setting Environment Variables for Powershell (Temporary)

Viewing environment Variables

PowerShell keeps a record of all environment variables in the env: virtual driver. The ls env: command lists all environment variables. Depending on the name of the environment variable, you can access it using $env:name.

PS> ls env:

Name                           Value
----                           -----
ALLUSERSPROFILE                C:\ProgramData
APPDATA                        C:\Users\Administrator\AppData\Roaming
CLIENTNAME                     SAMBP
CommonProgramFiles             C:\Program Files\Common Files
CommonProgramFiles(x86)        C:\Program Files (x86)\Common Files
CommonProgramW6432             C:\Program Files\Common Files
COMPUTERNAME                   SYSIN-NJ
ComSpec                        C:\Windows\system32\cmd.exe
DriverData                     C:\Windows\System32\Drivers\DriverData
GOPATH                         C:\Users\Administrator\go
HOMEDRIVE                      C:
HOMEPATH                       \Users\Administrator
LOCALAPPDATA                   C:\Users\Administrator\AppData\Local
LOGONSERVER                    \\SYSIN-NJ
NUMBER_OF_PROCESSORS           1OS Windows_NT Path C:\Windows\system32; C:\Windows; C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPo... PATHEXT .COM; .EXE; .BAT; .CMD; .VBS; .VBE; .JS; .JSE; .WSF; .WSH; .MSC; .CPL PROCESSOR_ARCHITECTURE AMD64 PROCESSOR_IDENTIFIER AMD64 Family23 Model 49 Stepping 0, AuthenticAMD
PROCESSOR_LEVEL                23
PROCESSOR_REVISION             3100ProgramData C:\ProgramData ProgramFiles C:\Program Files ProgramFiles(x86) C:\Program Files (x86) ProgramW6432 C:\Program Files PSModulePath C:\Users\Administrator\Documents\WindowsPowerShell\Modules; C:\Program Files\WindowsPo... PUBLIC C:\Users\Public SESSIONNAME RDP-Tcp# 103
SystemDrive                    C:
SystemRoot                     C:\Windows
TEMP                           C:\Users\ADMINI~1\AppData\Local\Temp\2
TMP                            C:\Users\ADMINI~1\AppData\Local\Temp\2
USERDOMAIN                     SYSIN-NJ
USERDOMAIN_ROAMINGPROFILE      SYSIN-NJ
USERNAME                       Administrator
USERPROFILE                    C:\Users\Administrator
windir                         C:\Windows
Copy the code

You can refer to CMD variables and replace the % variable name in CMD with the PowerShell format $env: variable name.

$env:windir: $env:windir:

PS> $env:windir
C:\Windows
Copy the code

$env:USERNAME: $env:

PS> $env:USERNAME
Administrator
Copy the code

PowerShell environment variables can also be used just like any other variable. Such as parsing directly into text.

PS> $env:ProgramFiles
C:\Program Files

PS> "Installation dir is $env:ProgramFiles\sysin"
Installation dir is C:\Program Files\sysin
Copy the code

Tip:Look at special methods for path

PS > (type env:path) -split '; '
# list split newline display
PS > (type env:path) -split '; ' | sls bin
Filter to search for entries containing bin
Copy the code

Create or update environment variables

$env: variable name =” variable value”

Overwrite if the original variable name already exists

PS> $env:Test1="sysin.org"
PS> $env:Test2="www.sysin.org"
PS> ls env:Test*

Name                           Value
----                           -----
Test1                       sysin.org
Test2                       www.sysin.org
Copy the code

Deleting environment variables

Syntax: del env: variable name. For example, to remove windir from an environment variable:

PS> del env:windir
PS> $env:windir
Copy the code

Don’t worry, this, like the set operation environment variable, is valid only for the current session.

Append environment variables

Env: variable name =”env: variable name =”env: variable name =” A variable’s value. “”

For example, it is common to append a PATH

$env:Path="$env:Path; C:\sysin"
Copy the code

3.2 PowerShell persists operating environment variables

The above operations on environment variables only affect the current PowerShell session and are not updated on the system, so there is no distinction between “user variables” and “system variables”. Instead, they operate on a combination of both.

To write environment variables to the system, you need to use the.NET method [environment]::SetEnvironmentvariable to manipulate environment variables.

First, let’s look at how to view the PATH in user variables and system variables respectively.

# user variables
PS> [environment]::GetEnvironmentvariable("Path"."User")
c:\powershellscript
# Ends with a semicolon in some versions of Windows 10
C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;

# System variables
PS> [environment]::GetEnvironmentvariable("Path"."Machine") C:\Windows\system32; C:\Windows; C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1.0\; C:\Windows\System32\OpenSSH\;# There are no semicolons in some versions of Windows 10C:\Windows\system32; C:\Windows; C:\Windows\System32\Wbem; C:\Windows\System32\WindowsPowerShell\v1.0\; C:\Windows\System32\OpenSSH\Copy the code

Fortunately, when writing environment variables, there is no problem with two semicolons, so when appending environment variables, the value of the original variable should be separated by semicolons, not semicolons at the end.

Write environment variables

# user variables
[environment]::SetEnvironmentvariable("Variable name"."Variable value"."User")

# System variables
[environment]::SetEnvironmentvariable("Variable name"."Variable value"."Machine")
Copy the code

Example: Create and append environment variables

The following uses the go environment variable configuration as an example:

Graphical Interface (Windows 10) : This computer –> Properties –> Advanced System Settings –> Advanced –> Environment Variables…

  • User variables:

    • New: GOPATH = %UserProfile%\ GOPATH (e.g. current user is C:\Users\Administrators)
    • PATH variable adds a %GOPATH%\bin
  • System variables:

    • New: GOROOT = C:\go
    • PATH added a %GOROOT%\bin

Powershell is implemented as follows:

[environment]::SetEnvironmentvariable("GOPATH"."$env:USERPROFILE\gopath"."User")
$(command)
$([environment]::GetEnvironmentvariable(" PATH ", "User"))
# Notice that entries in PATH end with a semicolon
[environment]::SetEnvironmentvariable("PATH"."$([environment]::GetEnvironmentvariable("Path","User")); %GOPATH%\bin"."User")

[environment]::SetEnvironmentvariable("GOROOT"."C:\go"."Machine")
$(command)
$([environment]::GetEnvironmentvariable(" PATH ", "Machine"))
[environment]::SetEnvironmentvariable("PATH"."$([environment]::GetEnvironmentvariable("Path","Machine")); %GOROOT%\bin"."Machine")
Copy the code