How long can a Windows environment variable be?
Why a long value can exist in the environment yet fail in cmd.exe.
Windows is a rather amusing operating system, full of internal contradictions. Environment-variable length limits have long been a source of trouble. RapidEE used to flag values longer than 2,047 characters, and later 4,096. So I wanted to check how things behave on newer versions of Windows…
I tested Windows 11 (build 26200) and Windows Server 2022 (build 20348). On both machines, the native SetEnvironmentVariableW API created a temporary variable in the process environment with a 1,000,000-character value, and PowerShell read it in full. That was the largest size I tested. So far, so good.
However, that’s where things got weird.
- In my tests,
cmd.exestopped reliably expanding values around 8,191 characters. - PowerShell read the value in full. However, Windows PowerShell 5.1 refused to create a 32,767-character value through
Environment.SetEnvironmentVariable, while PowerShell 7 on my machine created a value of one million characters.
In these tests, I was able to set a value one million characters long, but individual applications and APIs have their own limits.
So RapidEE now warns when a value exceeds 8,191 characters as a compatibility threshold for cmd.exe.
RapidEE
By