Try cmd / c and custom timestamp
To build on the answers of others here, it may be that the output file you want to create has a date or time embedded in the name of the output file. With CMD.exe this can be achieved as follows. Note that this method prints the string output of the internal Windows environment variables and cuts them based on the position of the character, so it may be wrong for the Windows area that you are using. This method is limited to working with one area of ββWindows. For example, what works for the United States may not be successful for the United Kingdom due to differences in how the date and / or time is formatted for each region. PowerShell more efficient in that it can work with different areas of Windows, and PowerShell can call CMD.exe to run .cmd files, but this is beyond the scope of this answer.
Using CMD.exe
You can access the various components of date and time by editing the internal environment variables %date% and %time% as follows (again, the exact cutoff values ββdepend on the region configured in Windows):
- Year:
%date:~10,4% - Month:
%date:~4,2% - Day:
%date:~7,2% - Hour:
%time:~0,2% - Minute:
%time:~3,2% - Second:
%time:~6,2%
Suppose you want your log file to be named " Log_[yyyyMMdd]_[hhmmss].txt ", you should use the following:
Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt
To verify this, run the following command line:
cmd /c echo Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt
Combining everything together to redirect both stdout and stderr from your script to a log file with the current date and time, use the following command as a command line:
cmd /c YourProgram.cmd > Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt 2>&1
EDIT: Warning: the timestamp may contain a space!
As @ user25064 pointed out, sometimes times before noon can appear with the leading space in the hourly part of the time. Therefore, the file name must be enclosed in quotation marks to exclude the possibility of disconnecting the computer from the shell as follows:
cmd /c YourProgram.cmd > "Log_%date:~10,4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%.txt" 2>&1