I’ve written this trick every new job or position I miss out on the old standby, using batch script to capture command-line output to a dated log file. This post is so I’ll never have to reproduce it again.
C:\Users\YzOrg>echo %date:~10,4% %date:~4,2%
2010 11
C:\Users\YzOrg>echo hi > %date:~10,4%%date:~4,2%.txt
C:\Users\YzOrg>dir *.txt
Volume in drive C has no label.
Volume Serial Number is B8EE-D08D
Directory of C:\Users\YzOrg
11/24/2010 09:32 AM 5 201011.txt
10/01/2010 10:40 AM 210 SDK.txt
2 File(s) 215 bytes
0 Dir(s) 199,100,514,304 bytes free
C:\Users\YzOrg>set line=0123456789 ABCD 0123456789 ABCD0123456789 ABCD0123456789 ABCD0123456789
C:\Users\YzOrg>echo %line:~10,8%
ABCD 01
C:\Users\YzOrg>echo hi > demo%date:~10,4%%date:~4,2%%date:~7,2%.log & dir demo*.log
Volume in drive C has no label.
Volume Serial Number is B8EE-D08D
Directory of C:\Users\YzOrg
11/24/2010 09:50 AM 6 demo20101124.log
1 File(s) 6 bytes
0 Dir(s) 199,100,379,136 bytes free
C:\Users\YzOrg>set /?
Displays, sets, or removes cmd.exe environment variables.
SET [variable=[string]]
...<SNIP>
Use %~dp0 to get the full path of the current batch file. %0 is the scriptname argument, '~dp' are modifiers to get the drive and path of that argument, %~dp0.
Interesting FOR commands in cmd.exe :
FOR /F ["options"] %variable IN (file-set) DO command [command-parameters]
FOR /F ["options"] %variable IN ("string") DO command [command-parameters]
FOR /F ["options"] %variable IN ('command') DO command [command-parameters]
Rule: always turn off 'echo' in batch files using this first line:
@if not defined _echo echo off
Use 'set _echo=1' before calling the script to debug it (it will echo every command)
References: set /?, call /?, for /?, setlocal /?
View comments