Advanced Batch script tricks

Posted on Updated on

Writing out all the directories (or other set) to an external file. One line, comma separated (useful for creating simple CSV files)

for /d %%I in (*) do (
  echo.|set /p ="%%I,"
) >> directories.txt

Testing in command lane:

c:\>for /d %I in (*) do (echo.|set /p ="%I,") >>directories.txt

c:\>type directories.txt
Ant,dev,drvrtmp,Intel,PerfLogs,Program Files,Program Files (x86),Python25,Python26,Python31,svn,Users,Windows,

How to store an Environment variable which contains undefined env.variables for later use.

c:\>set format="Name:%name% Date:%birthday%"

Using in batch file, need double %%

set format="Name:%%name%% Date:%%birthday%%"

Now format contains only a “template”

c:\>echo %format%
"Name:%name% Date:%birthday%"

Later in your program you can set the missing environment variables

c:\>set name=Botond
c:\>set birthday=2010.05.01

and then, using format as a template, you can make the final record:

c:\>for /f "delims=" %I in ('echo %format%') do (set record=%I)

or using it in a Batch script:

for /f "delims=" %%I in ('echo "%format%"') do (set record=%%I)

Now the variable record contains the final result:

c:\>echo %record%
"Name:Botond Date:2010.05.01"
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s