问题
Having very little experience with Batchfiles, scripting and generally "coding", I quickly ran into a problem with a Batch I want to create.
The situation is as follows:
I have a folder, in which *.txt files are automatically inserted, and I wanted to move these files to different folders based on the names the files have. I did this with Robocopy and it works just fine. Then I discovered the possibility to log the stuff that Robocopy does. The Batch currently looks like this:
robocopy C:\Source C:\Target_Normal file*.txt /xf file022*.txt /mov /log+:LogNo.txt /ns /nc /np /r:1 /w:5
robocopy C:\Source C:\Target_Special file022*.txt /mov /log+:LogNo.txt /ns /nc /np /r:1 /w:3
This Batch has to be part of a Windows Scheduled Task, that has to run every Minute. Because there are a lot of files to be moved, the logfile will soon be very bloated. I now need a Logfile for every day, that the same Batch automatically creates the first time it runs on a new day. It would be perfect if the name of the newly created Logfile contained the Date it was created, of course. I want to put all of this above the robocopy lines. In pseudocode, I'd like to have something like this:
If currentDay has no Logfile yet ->
Create Logfile with Name Log+currentDate ->
else (nothing and continue?)
...if that makes any sense. I just don't know how to express that to work in a Batch.
回答1:
This batch demonstrates how to get the actual date with wmi and it splits that ISO date time into parts you can assemble to your liking.
@Echo off
SetLocal EnableExtensions EnableDelayedExpansion
:: Get Local date time
for /f "tokens=1-3 delims=.+-" %%A in (
'wmic os get LocalDateTime^|findstr ^^[0-9]'
) do Set _DT=%%A
Set "_yy=%_DT:~0,4%" & Set "_MM=%_DT:~4,2%" & Set "_dd=%_DT:~6,2%"
Set "_hh=%_DT:~8,2%" & Set "_nn=%_DT:~10,2%" & Set "_ss=%_DT:~12,2%"
:: Put your date time elements together
:: %_DT:~0,8% is yyyyMMdd
Set LogNo=Log_%_DT:~0,8%.txt
set _
Echo Logfile is : %LogNo%
Pause
robocopy C:\Source C:\Target_Normal file*.txt /xf file022*.txt /mov /log+:%LogNo% /ns /nc /np /r:1 /w:5
robocopy C:\Source C:\Target_Special file022*.txt /mov /log+:%LogNo% /ns /nc /np /r:1 /w:3
来源:https://stackoverflow.com/questions/41227141/create-file-with-current-date-in-filename-robocopy-logging