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>
Pitfalls with using %DATE% and %TIME% in filenames
Time and date from OS can have spaces. So put the log filename in its own variable and useSET MYVAR=%MYVAR: =0%
to replace any spaces from %DATE% and %TIME% to 0.
I recommend you follow this guidance, put StdErr redirection at the end of the line.
Here is the final snippet for use in scripts:
Code
set LOG_TIMESTAMP=%date:~10,4%%date:~4,2%%date:~7,2%-%time:~0,2%%time:~3,2%.JobName.log set LOG_TIMESTAMP=%LOG_TIMESTAMP: =0% echo starting at %date% %time% with log %CD%\log\%LOG_TIMESTAMP%
Output
starting at Tue 02/13/2011 8:26:57.99 with log C:\Users\YzOrg\log\20110213-0826.JobName.log
Other CMD Tricks
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.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 /?
Add a comment