1

I can't seem to find the right parameters of setx to modify an existing system environment variable. Basically, I have a variable that I want to append ".old" to.

Dumont
  • 111

1 Answers1

1

How do I append to an existing system environment variable using setx

Just add the extra data to the end of the variable.

Example:

> set _variable=foo

> echo %_variable%
foo

> setx _variable %_variable%bar

SUCCESS: Specified value was saved.

> echo %_variable%
foo

Note that is appears that the setx hasn't worked. This is because you must start a new cmd shell to see the change:

setx writes variables to the master environment in the registry, edits will only take effect when a new command window is opened - they do not affect the current CMD or PowerShell session.

Source - setx

Open a new cmd shell to see the change:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

> echo %_variable%
foobar

And we can see the correct value.


But I want to change the variable name. How do I do that?

You can't change the variable name directly as it is stored as a key value in the registry.

  • As a workaround, create a new variable with the new name, and then delete the old one.

  • setx doesn't have a delete option, so delete the variable from the registry.

Example:

setx _variable.old %_variable%
reg delete HKCU\Environment /F /V _variable

Open a new cmd shell to see the changes.


Further Reading

  • An A-Z Index of the Windows CMD command line
  • reg - Read, Set or Delete registry keys and values, save and restore from a .REG file.
  • setx - Set environment variables permanently, SETX can be used to set Environment Variables for the machine (HKLM) or currently logged on user (HKCU).
DavidPostill
  • 156,873