batch-file: Getting current yyyyMMdd date into an environment variable.
Posted by jpluimers on 2010/08/04
This seems to be a recurring question on a lot of forums:
How to get the current date as yyyyMMdd into environment variable datestring in a regional independent way?
A lot of solutions are using construct around the %date% environment variable similar to this:
for /f "usebackq tokens=1,2,3,4 delims=- " %%i in (`echo %date%`) do ( set datestring=%%l%%k%%j echo %%i echo %%j echo %%k echo %%l ) echo %datestring%
There are two things wrong with this kind of solution:
- It depends on the order of fields inside the %date% environment variable
- It depends on the delimiter inside the %date% environment variable (specified by delims in the above example)
(note: the %date% environment variable has the same format as the date command).
For sytems having Powershell installed, this is a possible solution:
for /f "usebackq" %%i IN (`Powershell Get-Date -f "yyyyMMdd"`) DO ( set datestring=%%i echo %%i echo %%j echo %%k echo %%l ) echo %datestring%
This uses the for command trick to parse the output of another command.
You might think there are easier ways of sharing environment variables between Powershell and cmd batch-files, but there seem to be none.
In fact the other way around involves an even more complex way involving a temporary file.
If you do know about an easier way to get environment variables from PowerShell to cmd batch-files, please do comment below :-)
–jeroen
PS: I’m fully aware that if you start using PowerShell, it is a good thing to start moving your cmd batch-files to PowerShell as well.
Two things: time, and a lot of cmd batch-file depending on quirks that are difficult to get rid of.






Leave a comment