26

After some reseach, I found out that length limits for names are 255 and for values 32767 characters.

But which characters are allowed for names?
And which characters are allowed for values?

Robin Green
  • 32,079
  • 16
  • 104
  • 187
joe
  • 8,344
  • 9
  • 54
  • 80

3 Answers3

27

About variable values: you can use most characters as variable values, including white space. If you use the special characters <, >, |, &, or ^, you must precede them with the escape character (^) or quotation marks. If you use quotation marks, they are included as part of the value because everything following the equal sign is taken as the value.

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true

Check section "Setting environment variables".

About variable names: in my opinion, for best compatibility with every application, you should limit yourself to letters, numbers, underscore (_) and minus (-).

I'm quite sure that all POSIX valid characters for files are ok, but I did not found any evidence of this.


Concerning variable names names we need to also accept parenthesis since %ProgramFiles(x86)% is a well-known envar. From my experiments it seems that in addition to letters and digits characters, these characters are valid _(){}[]$*+-\/"#',;.@!? and these characters are not valid %<>^&|=:.

I didn't do an exhaustive search but just tested most common non alphanumeric characters.

And just for the fun of it you can name an envar %_(){}[]$*+-\/"#',;.@!?%:

C:\>set _(){}[]$*+-\/"#',;.@!?=xyz

C:\>echo %_(){}[]$*+-\/"#',;.@!?%
xyz
Patrick from NDepend team
  • 13,237
  • 6
  • 61
  • 92
Ghigo
  • 2,312
  • 1
  • 18
  • 19
7

It seems like <>^&| are also valid characters, as long as they are properly escaped:

C:\>set ^<^>^^^&^|=xyz

C:\>echo %<>^&|%
xyz
user368683
  • 360
  • 3
  • 7
3

It seems that the only prohibited character is equal ("=") sign - from https://learn.microsoft.com/en-us/windows/win32/procthread/environment-variables:

The name of an environment variable cannot include an equal sign (=).

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Evgeni A.
  • 31
  • 1