Thursday, March 27, 2008

Writing a timestamp in Batch using WMIC

WMIC(Windows Management Instrumentation Command-line) is one of the less used, but very cool & powerful features of windows.

Try this from a command prompt for an example:

wmic process

One of the things that sucks in windows is trying to use system date/time strings within a batch file, but WMIC makes this less painful:
:: Use WMIC to retrieve date and time
FOR /F "skip=2 tokens=2-7 delims=," %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:csv') DO (
SET /A SortDate = 10000 * %%F + 100 * %%D + %%A
SET /A SortTime = 10000 * %%B + 100 * %%C + %%E

:: display timestamp
echo %SortDate%%SortTime%



xparrot said...

Awesome Tip! I previously used realdate but it isn't supported for 64 bit.

Anonymous said...

It would be better to do sorttime without the SET /A math so as to avoid the discard of leading zeros, otherwise that code is like Cinderella's chariot and breaks down horribly at midnight.

IF %%B LSS 10 SET hr=0%%B
IF %%B GEQ 10 SET hr=%%B
... et cetera for minutes and seconds, then ...
SET sorttime=%hr%%min%%sec%

It'll always look right that way, e.g. 00:01:30 will be sorttime 000130 and not 130.