• Happy holidays, folks! Thanks to each and every one of you for being part of the Tom's Hardware community!

Question (CMD) Saving a file to a variable not working ?

Dec 30, 2021
2
0
10
Hello,
I'm trying to write a batch file that relies on contents of a file being saved as a variable. I've looked for solutions on multiple forums, and none of them are working anymore. I'm using Windows 10 on a virtual machine in VirtualBox. This is what I've done:

cmd-file-to-variable.png


This is my first time writing batch files in a really long time, and I forgot a lot, so when you write a comment saying how I can fix this, please write code that actually writes the above command into a file and saves it as the above variable, not code that saves another command into another variable. I forgot a lot, so please be patient with me. Thanks a lot for your help already.
 
This will do sort of what you want. However, the content is a single line as each lines EOL is not processed.
Code:
@echo off
set mylist=
for /f "delims=" %%a in ('type text.txt') do set mylist=!mylist! %%a
echo %mylist%

Output:
Code:
User accounts for \\TANYA-PC ------------------------------------------------------------------------------- Administrator            DefaultAccount           Guest                     Tanya                  WDAGUtilityAccount        The command completed successfully.

A more elegant solution that will give you output that honors EOL's is (don't remove the blank lines after eol^):

Code:
@echo off
setlocal EnableDelayedExpansion
set eol=^


set mylist=
for /f "delims=" %%a in ('type test.txt') do set "mylist=!mylist!%%a!eol!"
echo !mylist!
endlocal

output:
Code:
User accounts for \\TANYA-PC
-------------------------------------------------------------------------------
Administrator            DefaultAccount           Guest
Tanya                  WDAGUtilityAccount
The command completed successfully.

hth
 
Last edited by a moderator:
A more elegant solution that will give you output that honors EOL's is (don't remove the blank lines after eol^):

Thanks! I've tried the second solution, and unfortunately, the code won't finish running without opening Notepad for some reason. Is there any way to work around that? Here's a screen recording of what happened.
 
It shouldn't do that - and doesn't do that to me.
I couldn't get your screen recording to open.
Copy the code to a text file and call it, eg test.cmd. Make sure it's saved as UTF-8 and run from a command window.