Wednesday, April 20, 2011

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

hi,

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

From stackoverflow
  • 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 ">>")

    Maddy : hi, No actually i get a value returned to ScriptOut(Returned frm vbs) which should be written into a text file.When i run this above code,i just get ECHO is OFF in the myfile.txt
    Stanislav Kniazev : Then the blank line is your problem as Johannes Rössel pointed out.
    Maddy : I didnt get it Johannes??.Which blank line could be the problem.Why am i getting ECH is OFF in my Myfile.txt.??
    Lucas Jones : The reason you are getting ECHO OFF is that ECHO is being passed noting, or just whitespace (ie a blank line). In this case, ECHO prints whether command-echoing is turned on. (It just so happens that you turned off that with your 'ECHO OFF' at the top) This has no effect on whether it will redirect.
    Joey : I elaborated a little more, hopefully that made it somewhat clearer
  • 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.

0 comments:

Post a Comment