Leonardo Meinerz Ramos
Leonardo Meinerz Ramos

Reputation: 370

Environment variables not working properly

I'm trying to run an application that reads an environment variable that contains a JSON with about 22k characters. The project setup tells me to use $(cat ./path/to/file) to correctly configure it, but as I'm using windows, this commands do not work.

I've tried copying the contents of the file to the variable using the GUI Environment Variable, but its input truncates the value to a certain limit which is not even on half of the file. After this I tried setting the variable using the Powershell with the command:

$env:myvar = iex '$(type path/to/file)'

and then saving the result with:

[System.Environment]::SetEnvironmentVariable('MYVAR', $env:MYVAR, [System.EnvironmentVariableTarget]::Machine)

After these commands, Powershell is able to print the result correctly but CMD still prints only part of the value when I echo it.

This is very odd because the regedit shows the correct value as suggested here.

The application still can't process the value because it is not complete.

Is there any fix for this?

Upvotes: 1

Views: 3507

Answers (2)

mklement0
mklement0

Reputation: 437428

Note: This answer applies to Windows.

tl;dr

  • While you can store up to 32,766 characters in a single environment variable, the standard retrieval mechanisms in cmd.exe and PowerShell / .NET (as of v7.1 / 5.0) support only up to 4,095.

  • A workaround in PowerShell is possible, but ultimately it comes down to whether the target executable that is meant to read an environment-variable value supports reading values up to the technical maximum length.


  • The technical limit for the number of characters in a single environment variable is 32,766 (32KB = 32768, minus 2).

    • Starting with Windows Server 2008 / Windows Vista, there is no longer a limit on the overall size of the environment block - see the docs.
  • However, depending on how the environment-variable is retrieved, the limit may be lower:

    • Both cmd.exe and PowerShell, as of v7.1 / .NET 5.0, support retrieving at most 4,095 characters.

    • However, in PowerShell you can retrieve longer values, assuming the variable of interest is defined persistently in the registry, and assuming that you know whether it is defined at the machine or user level; e.g., for a MYVAR environment variable:

      • At the machine level:

         Get-ItemPropertyValue 'registry::HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' MYVAR 
        
      • At the user level:

         Get-ItemPropertyValue registry::HKEY_CURRENT_USER\Environment MYVAR
        

Upvotes: 6

theVerySharpFlat
theVerySharpFlat

Reputation: 89

try the type command. It is the windows equivalent of the unix cat command. This means storing the json inside of a seperate file and using the command "type <path_to_file>".

Upvotes: 0

Related Questions