Maddy
Maddy

Reputation: 141

Return a value from batch files (.bat file)to a text file

I have a .bat file shown below

@echo off 
for /f "delims=" %%a in ('C:\MyProj\Sources\SearchString.vbs') do (
set ScriptOut=%%a)
#echo Script Result = %ScriptOut%
echo %ScriptOut% >C:\ThreePartition\Sources\myfile.txt

I want my output variable which is ScriptOut to be stored into a text file. Can anyone suggest any method to be added to my existing batch file.

Thanks Maddy

Upvotes: 3

Views: 10349

Answers (2)

Joey
Joey

Reputation: 354694

The for loop you have there executes that script and runs for every line the script returns. Basically this means that your environment variable %ScriptOut% contains only the last line of the output (since it gets overwritten each time the loop processes another line). So if your script returns

a
b
c

then %ScriptOut% will contain only c. If the last line is empty or contains only spaces iot will effectively delete %ScriptOut% which is why when you do an

echo %ScriptOut%

you'll only get ECHO is on. since after variable substition all that's left there is echo. You can use

echo.%ScriptOut%

in which case you'll be getting an empty line (which would be what %ScriptOut% contains at that point.

If you want to print every line the script returns to a file then you can do that much easier by simply doing a

cscript C:\MyProj\Sources\SearchString.vbs > C:\ThreePartition\Sources\myfile.txt

or use >> for redirection if you want the output to be appended to the file, as Stanislav Kniazev pointed out.

If you just want to store the last non-empty line, then the following might work:

for /f "delims=" %%a in ('C:\MyProj\Sources\SearchString.vbs') do (
  if not "%%a"=="" set ScriptOut=%%a
)

which will only set %ScriptOut% in case the loop variable isn't empty.

Upvotes: 2

Stanislav Kniazev
Stanislav Kniazev

Reputation: 5488

Do I understand correctly that your file gets overwritten and you want it appended? If so, try this:

echo %ScriptOut% >> C:\ThreePartition\Sources\myfile.txt

(note the double ">>")

Upvotes: 2

Related Questions