1

I want to name a file using the current date and time in a specific format.

To do so, I have the following code to set %datetime% to the format I want.
Example: 2017-06-19 05_00_00

for /f %%a in ('powershell -Command "Get-Date -format yyyy-MM-dd\ HH_mm_ss"') do set datetime=%%a

This isn't quite working. I'm 99% sure it is due to the space between the date and time, which I want.

What is the error, and how can it be fixed?

(Note that I cannot depend on WMIC being available, so calling Powershell is probably the best solution. Regardless, I'm interested in learning how to get this specific code to work.)

  • 1
    [How to get current datetime on Windows command line, in a suitable format for using in a filename?](https://stackoverflow.com/questions/203090/how-to-get-current-datetime-on-windows-command-line-in-a-suitable-format-for-us) shows how to get local date/time in a region independent format using __WMIC__ command and reformat it with environment variable string substitutions to the wanted format in a batch file. So it is possible to get date and time in the format you want directly in the batch file with just 2 lines without using PowerShell at all. – Mofi Jun 19 '17 at 06:08

1 Answers1

2

You can try with any of these

for /f "delims=" %%a in ('
    powershell -Command "Get-Date -format 'yyyy-MM-dd HH_mm_ss'"
') do set "datetime=%%a"

for /f "tokens=*" %%a in ('
    powershell -Command "Get-Date -format 'yyyy-MM-dd HH_mm_ss'"
') do set "datetime=%%a"

for /f "tokens=1,2" %%a in ('
    powershell -Command "Get-Date -format 'yyyy-MM-dd HH_mm_ss'"
') do set "datetime=%%a %%b"

Changes from original code

  1. The format string has been quoted
  2. The for /f command tokenizes the lines being processed using spaces and tabs as delimiters, retrieving by default only the first token in the line (in your case, the date). As your output has two space separted tokens, we need to disable the tokenizer (first sample, by clearing the delimiters list), request all the tokens in the line (second sample) or request only the needed tokens (third sample)
MC ND
  • 69,615
  • 8
  • 84
  • 126