SimonS
SimonS

Reputation: 1973

Batch: syntax error on %time% with environment variables

I'm running a Batch script on a German Win7 environment with the following variable:

%date%_%time:~0,2%-%time:~3,2%-%time:~6,2%

This script works quite well from 10:00 until 23:59. Between 0:00 and 9:59 i get a Syntax error (I suppose because the time has only one digit before the ":")

Can someone help me with this?

Thx!

Upvotes: 4

Views: 207

Answers (1)

JosefZ
JosefZ

Reputation: 30153

Still locale dependent:

set "_datetime=%date%_%time:~0,2%-%time:~3,2%-%time:~6,2%"
set "_datetime=%_datetime: =0%"

For locale independent solution (and yes, without _ and - by then):

for /F "tokens=2 delims==" %%G in (
    'wmic OS get LocalDateTime /value'
) do @for /F "tokens=*" %%x in ("%%G") do (
    set "_datetime=%%~x"
)
set "_datetime=%_datetime:~0,14%"
goto :eof

Here the for loops are

  • %%G to retrieve the LocalDateTime value;
  • %%x to remove the ending carriage return in the value returned (wmic behaviour: each output line ends with 0x0D0D0A instead of common 0x0D0A).

See Dave Benham's WMIC and FOR /F: A fix for the trailing <CR> problem

Upvotes: 2

Related Questions