Monday, December 3, 2012

Include contents of .txt file within a .bat file

I have stored some batch file commands in a .txt file.  If I reference that file from another .bat file (thru a "call") the .txt file simply opens in Notepad.  I want to execute these commands from another .bat file; that is to say, I want to "include" them in another batch file.

This would have been simple if I had ended the second file with .bat instead of .txt, but I had a good reason for not doing so.  I want the user to be able to view the contents of this .txt file after the fact, so I want it to open (when selected through a custom built UI) in Notepad, not execute.  I found some very sophisticated solutions on the web, but they were much too complicated.  Here is my trivial solution.

Contents of to_be_included.txt:


   @set "first=x"
   @set "second=y"

Contents of do_it.bat:

   @echo Start %0
   @type to_be_included.txt > to_be_included.bat
   @echo  exit /b >> to_be_included.bat
   @call to_be_included.bat
   @echo I got %first% and %second%.
   @echo End %0

Results of running do_it.bat:

   Start do_it
   I got x and y.
   End do_it


Yes, it creates a superfluous .bat file, but for my purposes that's not a problem as my app will clean up after itself anyway.

No comments:

Post a Comment