Tuesday, November 13, 2007

Datestring in batch regardless of regional date setting

A while back I mentioned a collection of advanced batch commands, and today I actually needed the good old env variable %TimeStamp%, so here it is:

@echo off
:: Works on any NT/2K/XP machine independent of regional date settings
FOR /f "tokens=1-4 delims=/-. " %%G IN ('date /t') DO (call :s_fixdate %%G %%H %%I %%J)
for /F "delims=: tokens=1-2" %%i in ('time /t') do (call :settimeenvvars %%i %%j)
goto :s_print_the_date

:s_fixdate
if "%1:~0,1%" GTR "9" shift
FOR /f "skip=1 tokens=2-4 delims=(-)" %%G IN ('echo.^date') DO (
set %%G=%1&set %%H=%2&set %%I=%3)
goto :eof

:settimeenvvars
set hour=%1
set minute=%2
IF 1%hour% LSS 20 SET hour=0%hour%
IF 1%minute% LSS 20 SET minute=0%minute%
goto :eof

:s_print_the_date
set timestamp=%yy%%mm%%dd%
if "%1" == "dateonly" goto :end
set timestamp=%timestamp%-%hour%%minute%

:end
echo %timestamp%


I have mentioned it before, but much inspiration for batch can be found at robvanderwoude.com.

One Windows program I have never had a use for before is c:\windows\system32\attrib.exe, which displays or changes file attributes:

ATTRIB [+R -R] [+A -A ] [+S -S] [+H -H] [drive:][path][filename] [/S [/D]]

+ Sets an attribute.
- Clears an attribute.
R Read-only file attribute.
A Archive file attribute.
S System file attribute.
H Hidden file attribute.
[drive:][path][filename]
Specifies a file or files for attrib to process.
/S Processes matching files in the current folder and all subfolders.
/D Processes folders as well.

Example:
attrib file://servername/d$/%2 -r -s -h

No comments: