How to set an environment variable PERMANENT from cmdline?

Discussion in 'Windows 7 Help and Support' started by pstein, Oct 24, 2013.

  1. pstein

    pstein Honorable Member

    Joined:
    Mar 20, 2010
    Messages:
    347
    Likes Received:
    0
    If I open a CmdPrompt and type

    set myvar=foobar

    then this environment variable is set only for the time the CmdPrompt exists and is only visible INSIDE the CmdPrompt.

    How do I set such an environemnt variable from CmdPrompt (!) but permanently (forever) for

    - a certain user
    - whole system/computer?

    Again: I don't want t use Windows GUI to set the var. Everything should take place from cmdline.
    Entering a var value to Registry would be acceptable as well.

    How does it work?

    Peter
     
  2. patcooke

    patcooke Microsoft MVP
    Staff Member Premium Supporter Microsoft MVP

    Joined:
    May 16, 2010
    Messages:
    5,456
    Likes Received:
    268
  3. Josephur

    Josephur Windows Forum Admin
    Staff Member Premium Supporter

    Joined:
    Aug 3, 2010
    Messages:
    1,019
    Likes Received:
    125
    setx works great, however when I have used it before it seemed the variable did not take effect in the current command prompt space, upon launching a new command prompt however the variable was there and contained the value.

    e.g. "setx test foobar", then type set and you may not see the variable there as a system variable. However if you run a new command prompt, and type set you will see that TEST=foobar.
     
  4. Josephur

    Josephur Windows Forum Admin
    Staff Member Premium Supporter

    Joined:
    Aug 3, 2010
    Messages:
    1,019
    Likes Received:
    125
    You may also want to look at SETLOCAL and ENDLOCAL commands within a batch script. They do not do exactly what you want, but they do allow a subscript to be called within the current one, that can set a variable for the current command space, therefore that variable lives until the originating .bat or .cmd file is closed.

    This may allow you to pass variables between sub scripts, and not store them permanently. If you absolutely need permanent variable then setx seems to be the way to go, however you would have to launch a new cmd.exe afterwards to see the variable.
     

Share This Page

Loading...