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

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Great explanations!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.