Often I need to load the content of a file into a Windows Command Prompt variable. This is useful when writing batch scripts where the return value from one program is used as input for another program. At other times I need to process a json file to load just a value into a variable.

Note: There is a limit to the size of variables. I think the limit is 1024 bytes.

Let’s start with a sample test file “testfile”:
This is a test file line 1
This is a test file line 2
This is a test file line 3
And another sample test file “testfile.json”:
{
  "creationTimestamp": "2018-10-25T16:31:48.172-07:00",
  "description": "",
  "id": "6381188456147577995",
  "kind": "compute#instanceTemplate",
  "name": "instance-template-1"
}
Load the first line from testfile into a variable:
REM - load the first line from testfile
set /p T=<testfile
echo %T%

This outputs:

This is a test file line 1
Load the last line from testfile into a variable:
REM - load the last line from testfile
for /f "delims=" %%x in (testfile) do set T=%%x
echo %T%

This outputs:

This is a test file line 3
Load all lines from testfile.json into a variable:
REM - load all of the lines from testfile.json
set T=
SETLOCAL EnableDelayedExpansion
for /f "Tokens=* Delims=" %%x in (testfile.json) do set T=!T!%%x
echo %T%

This outputs:

{  "creationTimestamp": "2018-10-25T16:31:48.172-07:00",  "description": "",  "id": "6381188456147577995",  "kind": "compute#instanceTemplate",  "name": "instance-template-1"}
Load just a value from a json file:
REM - load just a value from a json file
jq .name testfile.json > out.tmp
set /p T=<out.tmp
echo %T%

This outputs:

"instance-template-1"
Load just a value from a json file without the quotes:
REM - load just a value from a json file without quotes
jq -r .name testfile.json > out.tmp
set /p T=<out.tmp
echo %T%

This outputs:

instance-template-1