How to use setx command in a windows batch file How to use setx command in a windows batch file windows windows

How to use setx command in a windows batch file


The Windows command line error:

ERROR: Invalid syntax. Default option is not allowed more than '2' time(s).Type "SETX /?" for usage.

Summary:

You are using a setx command and assigning it multiple tokens when only one is allowed.

How to reproduce this error on Windows:

Open a windows cmd terminal and enter these commands. This throws the error:

C:\Users\Charity>setx FANCYPANTS string with spacesERROR: Invalid syntax. Default option is not allowed more than '2' time(s).Type "SETX /?" for usage.

Do the same command, but quote your string like this:

C:\Users\Charity>setx FANCYPANTS "string with spaces quoted"SUCCESS: Specified value was saved.C:\Users\Charity>

The variable was set, restart the cmd terminal here to load changes.

C:\Users\Charity>echo %FANCYPANTS%string with spaces quoted

The environment variable is saved. Now delete it.

C:\Users\Charity>setx FANCYPANTS ""SUCCESS: Specified value was saved.

restart the cmd terminal here to load changes. Print contents again.

C:\Users\Charity>echo %FANCYPANTS%%FANCYPANTS%

the variable FANCYPANTS was deleted and no longer exists.


SETX requires values with spaces to be quoted, and quotes within the value must be escaped as \".

Best also to use delayed expansion to protect against special characters during the batch parsing phase.

The following will not only toggle the values for new CMD sessions, it will also toggle the value for the remainder of the batch script run. An implicit ENDLOCAL at the end of the script will revert to the old values within the current session once the script ends. If needed, the script can be modified to preserve the new values past the ENDLOCAL barrier.

@echo onsetlocal enableDelayedExpansionif "!PYTHONHOME:~-2!" == "24" (  set "PYTHONHOME=C:\Python33"  set "PATH=!PATH:Python24=Python33!") else (  set "PYTHONHOME=C:\Python24"  set "PATH=!PATH:Python33=Python24!")setx PYTHONHOME "!home!"setx PATH "!path:"=\"!"pause


The SETX command is very reliant on the syntax of the command. The following example shows the basic syntax to use to set the path environment variable:

SETX PATH "%PATH%;Path to new thing added" /M

This will also add the new path to the system registry, but still won't add it for the current session. Re-launch the terminal for it to take affect.