Batch File DIR Command to Text File Without Overwrite [duplicate] - batch-file

This question already has answers here:
How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name?
(30 answers)
Closed 1 year ago.
I'm trying to preserve the dates of files that I'm backing up onto an external drive, in the unlikely event that the dates get messed up for whatever reason (I had a previous experience where I lost date information and had no backup). I'm doing this through a batch file containing the following:
#ECHO OFF
cd E:\PCBackup
dir /s > dirlist.txt
I would simply run this batch file after running my backup using FreeFileSync. Then, if I need to, I can search the txt file for the filename and see its corresponding date.
However, when this batch file runs, if there is a previous dirlist.txt, then it is overwritten with the new dirlist.txt. So, in a scenario where the dates get messed up and I don't yet realize it, if I run this batch file, it will overwrite the previous dirlist.txt with one that has the messed up dates, and I'd lose the date information!
So, what I think I want it to do is, if dirlist.txt already exists, then create a new one, say something like dirlist1.txt, so that I can have several "backups" of the text file that I can manually delete if necessary.
I've seen that one can instead use >> with something like dir /s >> dirlist.txt to append to an existing file instead of overwriting, but I don't want to append if I don't have to, I'd still like to create a new file.
Is there a way to accomplish this? I'm also open to alternative/simpler ways of preserving the dates, if there are any. Please keep in mind that I know little about CMD commands or programming, outside of a computer science course I took years ago. Thank you.

You will be told there are umpteen duplicate ways to do this so in this 22 nd year of the 1st century :-) Windows has no native way of returning a sequential Iso Date the primary answer will be use powershell and for my locale it needs to be called in a suitable format, introducing a delay.
powershell get-date -format "{yyyy-MMM-ddTHH_mm+01Z}"
Note:- colons : are not allowed, and for me 20 seconds later on one machine (but it does get faster with use) and 12-5 seconds later on this one, I get
2021-07-07T21_55+01Z
but actually its now 2021-Jul-07 21:56
I have found that the MakeCab method is faster and reliable but again the format is not pure sequencing and the Jul will NOT appear before Dec in a file list without significant batch file processing.
2021-Dec-31 23:00:00.txt
2021-Jul-08 21:54:20.txt
So in a .cmd I prefer a more instant result thus my clock is set to International dates (You will need to look at your LOCALE clock setting bottom right for your own construction.)
set isodate=%date:~0,10%
instantly returns
isodate=2021-07-07 and I can then use that for filename
#ECHO OFF
cd E:\PCBackup
set "isodate=%date:~0,10%"
dir /s > %isodate%-dirlist.txt
dir returns includes 2021-07-07-dirlist.txt
If you want to run several times in a day use
#ECHO OFF
cd E:\PCBackup
set "isodate=%date:~0,10%"
set "isotime=%time:~0,2%-%time:~3,2%-%time:~6,2%"
dir /s > %isodate%T%isotime%+01Z-dirlist.txt
Amend that any way you wish for your timezone, thus your own clock whatever your date format be it :-
31/2021/12
look at the way I split %time :~ start#base 0 , # of chars %-
one example for an "English" clock date of 31/12/2021 would be simply reverse to
"isodate=%date:~6,4%-%date:~3,2%-%date:~0,2%"
For American %date%=Thu 07/08/2021 use
"isodate=%date:~10,4%-%date:~4,2%-%date:~7,2%"

Related

Windows batch file ren using date variable

Learned batch a while ago in school, haven't ever used it until now b/c I had an idea. Just for fun I wanted to mess around with powercfg batteryreport with my new laptop, but I want to archive. I was going to try and figure out how to have the file powercfg batteryreport spits out changed in some sort of numerical order but I don't even know where to begin, so I decided to just make a new line that takes the current file created and adds the date. All of this is taking place inside of a special folder I created, so pathing isnt necessary.
#echo off
powercfg batteryreport
rename "battery-report.html" "batteryreport %date%.html"
This exact script works without the date variable, but never with it in, but of course I need a variable present in order to have multiple reports saved, as opposed to it writing over itself every time. I've tried messing with all spacings, quotes vs no quotes, no luck. Help (or a better way, preferably with explanation) would be greatly appreciated.
In all likelihood, your date format contains / which is illegal in a filename.
Use %date:/=-% in place of %date%. this converts each / to - (see set /? from the prompt for docco)
Equally, you could use %time::=.% o convert the time to a version usable in a filename.
To remove dayname, you need to use an intermediate variable:
set "dateonly=%date:* =%"
ren ... "...%dateonly:/=-%..."
The * means "all of the characters up to and including the first space" and this is replaced by nothing (the string following the =)
see set /? from the prompt for details.

Rename .bak file to include date that was 7 days in the past

You'll have to forgive me as I am a beginner when it comes to batch file and Powershell scripting.
We have a backup solution with SQL that is currently being tested, which will perform Full backups once a week and then Differental backups for the reminder of the weekdays. As part of the restore process, we have a Windows batch script file in place which will rename the Full backup file before compressing it with 7Zip. The rename portion of the script looks like this:
cd C:\SQL Backups\Production Backups\eStart_Good
set date=%date:~-4%_%date:~3,2%_%date:~0,2%
ren *%date%* eStart_Good_FullBackup.bak
As this command will get run once a week on the night of a Full backup, it looks for today's date in the form of eg. 2016_03_02 because that's how the naming convention is set when backing up from SQL. This works as it should do.
However, what I want to happen after a Full backup from SQL as occurred is rename the previous eStart_Good_FullBackup file by taking out the 'FullBackup' portion of the name and replace with the date 7 days previous to today's date. So if the next Full backup is set to run on 04/03/2016, I want it to show up in the file name as 2016_02_26 for example.
I know with the rename command I need to change it to:
ren FullBackup eStart_Good_%date%.bak (FullBackup being a wild card.)
But, I've tried a number of combinations to change the set date variable and I keep getting the wrong numbers or pieces of code when echoing the variable.
set date=%date:~-4%_%date:~3,2%_%date:~0,2%
Does anyone have any advice they can give me please?
Working with dates in batch scripts is... complicated. Powershell might be much simpler way for you to work with this. However, sometimes Powershell isn't an option and you just need to do it with a batch script. Here's a script I wrote for a how to figure out 'yesterday': How do I find last Sunday's date and save it in a variable in a Windows batch file. You can make it loop seven times to get seven days ago.
Hope this helps.

List a directory folder to a variable

I felt it was better to ask this separately rather than expect an answer from my comment on my previous post.
I already have variables set for the directory number %jobn% which is unique is there a way I can search for the unknown element to add to another variable, I know via the command line I can run Dir D09854* and I will get a single report with the full name, can this be collected somehow and add to a named variable?
S:\SWDA\HBOS>dir d09854*
Volume in drive S is Images
Volume Serial Number is FE8F-38FE
Directory of S:\SWDA\HBOS
18/02/2013 10:29 <DIR> D09854_Parent Test
I want to add the elements after "_" to a variable %DirDesc% so I can create the full path by combining %jobn%%DirDesc% to get "D09854_Parent Test"
dir d09854* /b will recover the full folder name in one line, without the extra cruft, if that's any use? What are you writing this widget in?
Does it have to be Good Old Fashioned DOS, or can the newer Command extensions be used?
With limited old DOS, I can't think of a way to get that into a SET Variable without piping it to a temporary batch file, having first ECHO'd a set variable= into it, and using >> in the pipe to append to it... and then CALL the temporary batch file to execute the command!

create a batch file which copies text files of specified date

I want to create a batch file which copies text file by taking user input. As an input user give from date and to date. The name of the text files are like: error_log_04_06_2011
Now for example I want data from 04/06/2011 to 07/06/2011, so i can do that by using xcopy command like this
#ECHO OFF
SET /P f=Please Enter from date(m-d-yyyy):
SET /P t=Please Enter to date(mm-dd-yyyy):
mkdir d:\bkp
xcopy /S /D:%f% /EXCLUDE:%t% C:\Emulator\Log_Data d:\bkp
This will copy all the file from the date mentioned. Now I want to give "to" date also.so i can copy files of a certain period.
One approch is that I use delete command and delete extra files that are copied. But Delete command doesnt have any switch regarding date. So plz help.....
Unfortunately, there isn't much that can help in this area built-in to batch/cmd. dir can take a flag to order its output by modified time, but I'm guessing you want it to depend on just the filenames and it still wouldn't give you the range you want.
The filename you have shown isn't sortable. If they were named in YYYY_MM_DD format, you could find the files in the date range with sort and a for loop.
Without that, you will end up needing to do date math to generate each individual date in your range, convert each date to your filename format, and pass that to copy.
Rob Van Der Woude has a good list of date functions in batch, including the harder date math. It would be a good place to start. http://www.robvanderwoude.com/battech.php#Time
I haven't tried it, but you could use the xcopy /d and /l switches to generate lists of files that are dated after a certain date to avoid doing the maths.
After the xcopy from the first date you could drive a delete in a for /l loop from a list of file dated after the second date.

How to get a UNIVERSAL Windows batch file timestamp

I'm having trouble generating a timestamp in a Windows batch file, because I get diferent date formats on different Windows versions.
My machine:
>echo %date%
>Tue 11/17/2009
Friends machine:
>echo %date%
>11/17/2009
I guess there has to be some way of getting the date (11/17/2009) from both strings using for /f. I've been trying and googling and can't find the answer.
Is there another way to get a timestamp without using %date%?
Check out doff.exe. I use this a lot for getting timestamps for naming log files. From its web site:
DOFF prints a formatted date and time, with an optional date offset, (e.g -1 prints yesterday's date, +1 prints tomorrow's date). To view all the options available, execute "doff -h". I typically use this utility for renaming log files so that they include a timestamp, (see the third example below). This code should compile under Unix/Linux, as well as DOS.
Sample commands:
C:\>doff
19991108131135
With no parameters the output is the current date/time in the following format: yyyymmddhhmiss
C:\>doff mm/dd/yyyy
11/08/1999
In the above example a date format specification is given.
#echo off
for /f "tokens=1-3 delims=/ " %%a in ('doff mm/dd/yyyy -1') do (
set mm=%%a
set dd=%%b
set yyyy=%%c)
rename httpd-access.log httpd-access-%yyyy%%mm%%dd%.log
The sample batch file above shows a neat way to rename a log file based on yesterday's date. The "for" command executes doff to print yesterday's date, (the "-1" parameter specifies yesterday), then extracts each component of the date into DOS batch file variables. The "rename" command renames "httpd-access.log" to "httpd-access-[yesterday's date].log"
Also check out Microsoft's now.exe, available in the Windows Server 2003 Resource Kit Tools. One bad thing I found out (the hard way) about it is it sets the ERRORLEVEL to the number of characters printed.
Looks like this:
c:\>now
Thu May 19 14:26:45 2011
Help:
NOW : Display Message with Current Date and Time
Usage : NOW [message to be printed with time-stamp]
NOW displays the current time, followed by its command-line arguments.
NOW is similar to the standard ECHO command, but with a time-stamp.
Use VBScript if you want to get independent date time settings:
thedate = Now
yr = Year(thedate)
mth = Month(thedate)
dy = Day(thedate)
hr = Hour(thedate)
min = Minute(thedate)
sec = Second(thedate)
WScript.Echo yr&mth&dy&hr&min&sec
Unfortunately, it can't be done directly, so you need to resort to hacks like GetDate.cmd.
There are lots of VBScript and small external commandline tools available too, which isn't something I'd take a dependency on unless you're already using something of that nature in your overall system.
Personally, I'd be trying to route around it by using PowerShell which neatly sidesteps the issue completely.
You don't need VBScript. You can do it with something like this:
echo %date:~-10,2%/%date:~-7,2%/%date:~-4,4%
Source
As I have posted in here:
Batch: Timestamp to UNIX Time
What about simple 1-line long C program returning UNIX timestamp? You can retrieve value from %errorlevel% in batch script.
#include <stdio.h>
#include <time.h>
int main(void)
{
return (int) time(NULL);
}
In my test in command prompt it worked:
C:\Users\dabaran\Desktop\cs50\src\C>.\time || echo %errorlevel% && set mytstamp=%errorlevel%
1419609373
C:\Users\dabaran\Desktop\cs50\src\C>echo %mytstamp%
1419609373

Resources