set environment variable from batch

0

When I set a environment variable envir using setx command, It seems to not actually 'set' in environment.

setx envir "windows"
if 1==1 (
    setx envir "unix"
)
echo %envir%
set

The set command displays a list of environment variable but it doesn't display the variable which was currently set by the previous line.

DDK

Posted 2014-10-15T13:02:11.510

Reputation: 129

Answers

1

In your example, the environment variable %ENVIR% is set to "windows". This is stored in the user-specific environment variables in the Windows registry. The change is not directly reflected in the environments of currently active processes.

To actually see this new setting via set command, you have to open a new command box using cmd.exe. The current command box does not automatically re-read changed settings from the registry. You could also use the system control SYSTEM and look under Extended Properties / Environment:

enter image description here

Axel Kemper

Posted 2014-10-15T13:02:11.510

Reputation: 2 892

or after running setx aaa 3, run set aaa=3 to set it in the current cmd prompt. Also, setx can be a bit dangerous, it's worth doing set>a.a first so if setx does write something a way you didn't intend, then you have a backup – barlop – 2016-07-09T10:30:16.343

0

Axel is correct.

setx stores the variable in the registry, but the change is not reflected in the environment of ANY running program (including the current one).

Here are some relevant parts of the output of setx /?:

C:\>setx /?

Description:
    Creates or modifies environment variables in the user or system
    environment. Can set variables based on arguments, regkeys or
    file input.

NOTE: 1) SETX writes variables to the master environment in the registry.

      2) On a local system, variables created or modified by this tool
         will be available in future command windows but not in the
         current CMD.exe command window.

      3) On a remote system, variables created or modified by this tool
         will be available at the next logon session. 

Kevin Fegan

Posted 2014-10-15T13:02:11.510

Reputation: 4 077