Compare current date with file modified date in batch file - batch-file

I have a requirement to create a batch file and that should work in windows 2003 server.
I have source folder "c:\Source" and destination folder "c:\Destination".
I want to check all the file modified dates in source folder:
If the file modified date is less than current date then that file will move into destination folder
Otherwise, do nothing.
Note: as my server is production server so, I am unable to install Resource kit and robocopy.exe. The only way is write the batch script.
Robocopy and forfiles are not working in Windows2003 server.

Update
Since you have forfiles on your server, this is easy. To check for files older than 1 day old, just use forfiles /D -1. For files over 2 days old, /D -2.
forfiles /D -2 /M *.log /P C:\Source /C "cmd /c move #file c:\Destination"
Enter forfiles /? in a console window for full syntax.
Original answer
Consider revising your requirement. Instead of saying "If file modified date is less than the current date", you should say, "If file modified date does not equal current date". That absolves you from having to do date math, and makes your task profoundly simpler. After all, the last modified date is not going to be a date in the future, right?
After that, it's a simple matter of scraping today's date from %date% and comparing it with the date from each file's %%~tX substitution property in a for loop. Type help for in a console window and see the last two pages for more information about this syntax.
I don't think there will be any locale date formatting issues with this. As long as your system's %date% variable is in the format of dayOfWeek Date and %%~tX is formatted as Date Time etc. then this script should work regardless of whether you handle dates locally as MM/DD/YYYY or YYYY/MM/DD or DD/MM/YYYY or something else. I hope.
#echo off
setlocal enableextensions
set "source=c:\Source"
set "destination=c:\Destination"
:: store today's date in %today%
for /f "tokens=2" %%I in ('echo %date%') do set "today=%%I"
for %%I in ("%source%\*") do (
rem :: scrape MM/DD/YYYY from %%~tI
for /f %%a in ('echo %%~tI') do (
rem :: compare the two dates
if "%%a" neq "%today%" (
echo %%~nxI: %%a does not equal %today%. Moving.
>NUL move /y "%%~fI" "%destination%"
) else (
echo %%~nxI: %%a equals %today%. Skipping.
)
)
)

Related

Batch scripts to copy files

I need help to create a batch file to copy files with specifc date and version. And my date will be as of yesterday. Example file name:- abcde-20150811-v1.csv
I have tried xcopy with /d:08-11-2015 ( it picks all files with date modified as 08-11-2015 MM-DD-YYYY)
Is there a way that my batch automatically picks the date and gets changed everyday.
You might take a look at this: How to get and display yesterday date?
If I were you, I'd go with a scripting language like Perl, or use PowerShell.
Try this piece of code, haven't tried it yet though.
#echo off
set completepath=c:\users\microsoft\desktop\source
set destination=c:\users\microsoft\desktop\destination
set /a yesterday=%date:~4,2% - 1
set yesterday_date=%date:~10,2%%date:~7,2%%yesterday%
FOR /R %completepath% %%G IN (*.csv) DO call :process "%%~dpG" "%%~nG"
pause >nul
:process
SET %name%=%~2
SET chkname=%name:*%yesterday_date%=?%
IF "%chkname:~0,1%"=="?" (
xcopy %~1 %destination% /y
)
You may change the completepath and the destination variable.

Rename file to creation time (batch file only)

Not sure this is possible with only a batch file.
I have a file named BaseFile.7z location is E:\Backup\C Drive Zip\BaseFile.7z
Is it possible to create a batch command that renames the file with its creation date? For example BaseFile - 02-19-2015.7z
I currently have a command that renames the file with the current date which I pasted below for reference, but thats not exactly what I'm looking for. I need creation date.
RENAME "E:\Backup\C Drive Zip\Jaipur.txt" "BaseFile - %date:/=-%.txt"
#ECHO OFF
SETLOCAL
SET "filename=U:\sourcedir\zzz.zzz"
IF NOT EXIST "%filename%" ECHO "%filename%" NOT found&GOTO :eof
SET "datepart="
FOR /f "tokens=1-3delims=/-:" %%a IN ('dir /tc "%filename%"') DO IF "%%c" neq "" SET "datepart=%%a-%%b-%%c"
FOR /f %%a IN ("%filename%") DO FOR /f %%d IN ("%datepart%") DO ECHO(REN "%%a" - "%%~na %%d%%~xa"
GOTO :EOF
The required REN command is merely ECHOed for testing purposes. After you've verified that the command is correct, change ECHO(REN to REN to actually rename the file.
Note that there is general sloppiness in the use of date-references. There are three dates on each file - actual create date (use /tc), last access (/ta) and last-written (/tw).
The process locates the file, then reads a dir listing with the appropriate date selected. The only or last line in the listing that will contain a third non-empty token is the date/time of the file in question, so datepart will acquire yyyy-mm-dd hh
the for/f %%a then applies the full filename to %%a ready for partitionig into its components and the for/f %%d assigns the first token from datepart (ie up to the space) into %%d.
Bang the components together, and the resut is reported...

robocopy command to move file based on created date

I have files in a folder 'FILEPATH', each file has different created date and modified date(modified date is less than created date).
I want to delete the files with created date greater than 10days. I used below command but it works on modified date.
ROBOCOPY %FILEPATH% %DUMPFOLDER% /move /minage:10
del %DUMPFOLDER% /q
On some forums its written that minage refers to created date but it's referring to modified date while executing. Am I doing something wrong here? Or is there any other alternate.
Unfortunately, there's no easy way to do this. The only commands of which I'm aware that can deal with file creation dates are dir /t:c and wmic datafile. There could be others, but there are none that simplify performing date math as forfiles or robocopy do.
Since date math in batch is cumbersome anyway, in this situation it makes sense to borrow from another runtime environment -- PowerShell, for example, or VBScript or JScript. The Windows Scripting Host FileSystemObject's File Object has properties for DateCreated, DateLastAccessed, and DateModified. With JScript, getting a file's age based on its DateCreated property is simply a matter of JavaScript Date() arithmetic.
Here, salt this .bat script to taste:
#if (#CodeSection == #Batch) #then
#echo off
setlocal
set "FILEPATH=c:\path\to\whatever"
set "age=10"
for %%I in ("%FILEPATH%\*") do (
call :getAge result "%%~fI"
setlocal enabledelayedexpansion
if !result! gtr %age% (
echo %%~nxI created !result! days ago and should be deleted
rem del "%%~fI"
) else (
echo %%~nxI is new ^(created !result! days ago^)
)
endlocal
)
goto :EOF
:getAge <return_var> <filename>
for /f "delims=" %%I in ('cscript /nologo /e:Jscript "%~f0" "%~2"') do set "%~1=%%I"
goto :EOF
#end
// JScript portion
var fso = WSH.CreateObject('scripting.filesystemobject'),
created = fso.GetFile(WSH.Arguments(0)).DateCreated,
age = new Date() - created;
WSH.Echo(Math.floor(age / 1000 / 60 / 60 / 24));
If you want something simpler, you could employ wmic datafile and get the first 8 digits of get creationdate like this cat does, but his solution doesn't take into account time of day. Such a method might inappropriately delete files that are 9 days, 23 hours old. Then there's also the problem of calculating days across new months. The JScript method above tests file age based on the current moment, rather than based on midnight; and will handle spanning months, years, and leap years with no conscious effort.

Batch File to Delete Files in a Folder

I understand that there are tons of questions on this site regarding the creation of a batch file that goes through the file in a specified folder and deletes them if it satisfies the condition stated.
However, I would like to tweak that a little bit. In my batch file, I would like to look at a folder, say C:\Dev and get all the files that are within the same month. After getting all those files, I want to sort through all the dates and delete everything except for the latest one. So if I have 5 files for January on that folder with dates January 1, 12, 20, 27, and 30, I would only keep the file dated January 30th and delete all the others.
Is this possible?
< lang-dos -->
#ECHO OFF
SETLOCAL
SET "targetdir=c:\sourcedir"
SET "pfname="
PUSHD "%targetdir%"
FOR /f "delims=" %%a IN ('dir /b /a-d /o:d "*" ') DO (
SET "fname=%%a"
SET "fdate=%%~ta"
CALL :process
)
POPD
GOTO :EOF
:process
:: reformat date - this depends on yout local date-format.
:: YY(YY)MM required - my format is dd/mm/yyyy
SET fdate=%fdate:~6,4%%fdate:~3,2%
IF NOT DEFINED pfname GOTO nodel
IF %fdate%==%pfdate% ECHO DEL "%targetdir%\%pfname%"
:nodel
SET pfdate=%fdate%
SET "pfname=%fname%"
GOTO :eof
This should work for you. The required DEL commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO DEL to DEL to actually delete the files.
First, the target directory is set up and pfname is cleared.
The PUSHD changes the current directory until the POPD is executed
the dir command outputs filenames only (/b), no directory names (/a-d) in date-order (/o:d). Each line sets fname to the filename and fdate to the filedate.
within :process, the date-string is manipulated. I don't know which format you use, but the basic formula is %variable:~startposition,length% where startposition starts at 0=first character. The idea is to have fdate in the format yyyymm
if pfname (previos filename) is not set, this is the first file found, so we don't delete that.
For every other file, if the filedate is the same as the previous filedate, then delete the previous filename.
The current filename/date is then recorded as the previous version.
Done!

How can I output weekday and month in batch (log files)?

I'm trying to setup 7zip for automated backups but I'm having trouble with output file names.
I tried using the %date% command but it just made 2 directories within my backup.
C:\Users\Desktop\Sun 11\07\2010.7z
How can I make it just log the day and month?
C:\Users\Desktop\Sun 11-07-2010.7z
Try
7z a %DATE:~-4%-%DATE:~4,2%-%DATE:~7,2%.7z *.* for (YYYY-MM-DD)
or
7z a %DATE:~7,2%-%DATE:~4,2%-%DATE:~-4%.7z *.* for (DD-MM-YYYY)
(*.* is the mask for the files to back up)
Are you using a bat-file? Look here http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/
You can use WMI to get your date details in a specific format. The problem with the output from date (and the %date% environment variable) is that it's very locale-specific.
If you execute:
wmic path win32_localtime get day^,month^,year^ /format:csv
you will see the output you need to process.
The following script will get you the yyyy-mm-dd format that you need (using the day of the week as the primary sort key is not a good idea):
#echo off
for /f "skip=2, tokens=2-4" delims=," %%a in ('wmic path win32_localtime get day^,month^,year^ /format:csv') do (
set /a ymd = 10000 * %%c + 100 * %%b + %%a
)
set ymd=%ymd:~0,4%-%ymd:~4,2%%ymd:~6,2%
echo %ymd%

Resources