Amazon Dies In Darkness
Amazon Dies In Darkness

Reputation: 5823

Formatting date and time in batch file using Powershell

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.)

Upvotes: 1

Views: 3477

Answers (1)

MC ND
MC ND

Reputation: 70923

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)

Upvotes: 2

Related Questions