Batch Script or PowerShell script to read the multiple values ​​of the text file and insert into variables

advertisements

I am looking for a batch script or PowerShell script that read values from a text file and place them in a script local variables.

For example the input file looks like:

input.txt
PARAM1=VALUE1
PARAM2=VALUE2
PARAM3=VALUE3

In the script I would like to place the values into three different variables like:

echo %variable1%
echo %variable2%
echo %variable3%

The output will be:

value1
value2
value3

I started the script like:

@echo off
setlocal
for /f "delims== tokens=1,2" %%G in ("input.txt") do set %%G=%%H  echo %G%

Please provide me some insights or ideas


I want to read values from a file and assign them to script local variables.

@echo off
setlocal
for /f "delims== tokens=1,2" %%G in ("input.txt") do set %%G=%%H  echo %G%

Your batch file is close, but need a couple of tweaks:

  1. In order to read the contents of input.txt in the for loop you need to type the file.

  2. You have a mistake in your echo command, it should be %%G not %%H.


To display the variable names

test.cmd:

@echo off
setlocal
for /f "delims== tokens=1,2" %%G in ('type input.txt') do (set %%G=%%H && echo %%G)
endlocal

Example usage:

F:\test>type input.txt
PARAM1=VALUE1
PARAM2=VALUE2
PARAM3=VALUE3

F:\test>test
PARAM1
PARAM2
PARAM3


To display the values of the variables, replace echo %%G with echo %%H

test.cmd:

@echo off
setlocal
for /f "delims== tokens=1,2" %%G in ('type input.txt') do (set %%G=%%H && echo %%H)
endlocal

Example usage:

F:\test>type input.txt
PARAM1=VALUE1
PARAM2=VALUE2
PARAM3=VALUE3

F:\test>test
VALUE1
VALUE2
VALUE3


Further Reading