How to move the latest files alone into a folder using cmd? - cmd

I have to move my latest files alone into a folder named 'archive' using cmd .how should i do it?
for ex: i have files which are created in may,june,july,aug and sep in my_folder.
now i need to move all the files which are created in may,june,july and aug into my_archive and sep files alone have to stay in my_folder.
i used move c:\my_folder*.* c:\my_archive. but this moves all the files. what should be the correct script for doing this?
second thing is , i am thinking of using task scheduler to run the batch file which has this move script? will this help?
Thanks,
ResKing

Assuming that your date format is MM/dd/yyyy this might work:
#echo off
set month=%date:~0,2%
set year=%date:~-4%
mkdir temp_folder
rem move this month's files out of the way
forfiles /d +%month%/01/%year% /c "%comspec% /c move \"#path\" temp_folder"
rem move all other files to my_archive
forfiles /d -%month%/01/%year% /c "%comspec% /c move \"#path\" my_archive"
rem restore this month's files
move temp_folder\*.* .
rmdir temp_folder

This batch will cycle through all old files (not from current month) and move them one by one to my_archive directory.
I'm creating a new file just in case there are no new files in this directory (I'm using a new file as a break rule for the loop). This file is deleted in the end of the batch file.
The dir parameters are to show only files and to sort them by date. you can additionally specify the timestamp you prefer:
/T:C - Creation
/T:A - Last Access
/T:W - Last Written
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
SET SRC_PATH=c:\my_folder
SET DST_PATH=c:\my_archive
SET MONTH=%date:~4,2%
SET YEAR=%date:~-4%
echo blah > !SRC_PATH!\to_delete.txt
for /f "skip=4 tokens=1,5 delims= " %%g in ('dir /A:-D /O:D !SRC_PATH!') do (
set date=%%g
set m=!date:~0,2!
set y=!date:~-4!
if !YEAR! gtr !y! (move !SRC_PATH!\%%h !DST_PATH!\%%h) else (
if !MONTH! gtr !m! (move !SRC_PATH!\%%h !DST_PATH!\%%h) else goto :end
) )
:end
del !SRC_PATH!\to_delete.txt

Related

Batch file to copy files from 1 day before and no more

imagine that I have 2 folders:
C:\FolderData (will be incremented daily with new files)
C:\FolderTemp (Needs to have only files from the day before executing, excluding hours/timestamp)
The FolderData will receive filenames that if not for date would be equals, as in:
SYS_PURCHASES_20170612.xls
SYS_PURCHASES_20170613.xls
SYS_PURCHASES_20170614.xls
If I run the .bat file today I need that only the SYS_PURCHASES_20170613.xls be copied over to FolderTemp.
I tried using robocopy but apparently it can't receive the same value for minage and maxage
robocopy "C:\FolderData" "C:\FolderTemp" /minage:1 /maxage:1
Also, if I try:
robocopy "C:\FolderData" "C:\FolderTemp" /minage:1 /maxage:2
It will bring both SYS_PURCHASES_20170612.xls and SYS_PURCHASES_20170613.xls, which is not what I need.
Other than that, I tried using forfiles but also with no avail.
forfiles /p C:\FolderData /D -1 /C "/C /copy /y #file C:\FolderTemp"
or even
forfiles /p C:\FolderData /D -1 /C "/C /copy /y C:\FolderData\#file C:\FolderTemp"
And other variables but it returns something along the line "the system can't return the specified file" times the number of files in the folder.
Note that there are other processes involved bellow that should be ignored, It's just that I can't figure out how to do the step above.
All steps my batch filed needs to do:
Copy from folder1 files from 1 day prior to folder2 (what I need help)
Remove last 9 digits from all files from folder2 (will remove the date, used the loop on this solution) so the file will be SYS_PURCHASES.xls
Move and replacing the files from folder2 to folder3 (using a simple move /y)
Since you want to touch the files from yesterday only, I would use forfiles, because this command only regards the date but not the time, when specifying the /D option. robocopy instead also regards the time, which is probably not what you want.
This is a possible way:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_SOURCE=C:\FolderData"
set "_TARGET=C:\FolderTemp"
set "_MASK=?*_????????.*"
set /A "_DAYS_AGO=1"
rem // Check given age and calculate interim value `PREV` needed for `forfiles`:
(if %_DAYS_AGO% LSS 0 set "_DAYS_AGO=0") & set /A "PREV=_DAYS_AGO+1"
rem // Let `forfiles` output the filtered files and capture them by `for /F`:
for /F "delims= eol=|" %%F in ('
rem/ Use two nested `forfiles` loops to filter for files of specified day: ^
^& forfiles /P "%_SOURCE%" /M "%_MASK%" /D -%_DAYS_AGO% ^
/C "cmd /C if #isdir==FALSE > nul 2>&1 forfiles /M #file /D -%PREV% || echo #file"
') do (
rem // Store current file name and extension:
set "FILE=%%~nF" & set "FEXT=%%~xF"
setlocal EnableDelayedExpansion
rem // Copy the file and remove the last 9 characters from its name:
> nul copy /Y "!_SOURCE!\!FILE!!FEXT!" "!_TARGET!\!FILE:~,-9!!FEXT!"
endlocal
)
endlocal
exit /B

windows batch script to copy files and move to backup directory

I have multiple folders that each contain a config folder. In the config folder there is a .cfg file and a backup folder. I would like to copy the .cfg file to the backup folder with a date extension.
Here is my folder structure:
\Folder1\config
folder1.cfg
\backup
\Folder2\config
folder2.cfg
\backup
\Folder3\config
folder3.cfg
\backup
Each of the above folders has a config folder. In each config folder there is a .cfg file and a backup folder. How can I step through each Folder*\config directory and copy the folder*.cfg file to the backup folder and rename it to folder3.cfg.yyyymmdd? I actually have about 40 folders that I would need to this for on a Windows server. Any help would be greatly appreciated.
REM
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
for /f "delims=." %%a in ('wmic OS Get localdatetime ^| find "."') do set "wmicdt=%%a"
SET "wmicdt=%wmicdt:~0,8%"
FOR /f "delims=" %%a IN ('dir /b /ad "%sourcedir%" ' ) DO (
IF EXIST "%sourcedir%\%%a\config\%%a.cfg" (
MD "%sourcedir%\%%a\config\backup" 2>NUL
COPY /b "%sourcedir%\%%a\config\%%a.cfg" "%sourcedir%\%%a\config\backup\%%a.cfg.%wmicdt%" >nul
)
)
GOTO :EOF
You would need to change the setting of sourcedir to suit.
The SET "wmicdt=%wmicdt:~0,8%" line selects the first 8 characters of the date/time string in wmicdt, which is yyyymmdd. If you want the time as well, simply omit this line.
Here is your answer.
#echo off
:loop
for /l %%g in (1,1,3) do (
copy "Folders\Folder%%g\config\Folder%%g.cfg" "Folders\Folder%%%g\config\Backup\"
rename "Folders\Folder%%g\config\Backup\Folder%%g.cfg" "Folder %date%.cfg"
timeout>nul 1
)
:end
cls
echo.
echo ========
echo = Done =
echo ========
echo.
pause>nul
I was trying to make a file with modification date as name but i had some problems with time (22-03-2012 12:22).
This 12 ==>:<== 22 is trouble me. I don't know how to get rid of this. So instead you have current date as a file name.
Sorry for my English.
Here is file with that batch and folders, so you can see how it works

Delete the oldest date entitled subfolder

I have this script which is created to backup a cube within an application. It runs every saturday and it created a sub folder within the application folder. Due to space requirements I've had to delete the oldest folder every week. I need to create a script to do that.
Here's the backup code:
:: Create folder for App Db if it does not exist
IF NOT EXIST %BACKUPDIR%%1"\"%2 GOTO MAKEDIR
GOTO CONT
:MAKEDIR
mkdir %BACKUPDIR%%1"\"%2
GOTO :CONT
:CONT
cd %BACKUPDIR%%1"\"%2
:: Get todays date
for /f "tokens=2,3,4 delims=/ " %%i in ('date /t') do (
set my_day=%%j
set my_month=%%i
set my_year=%%k )
set datestamp=%my_month%%my_day%%my_year%
::echo %datestamp%
:: Create date folder for app db
IF NOT EXIST %BACKUPDIR%%1"\"%2"\"%datestamp% GOTO MAKEDIRTIMEDATE
:MAKEDIRTIMEDATE
G:
cd %BACKUPDIR%%1"\"%2"\
mkdir %BACKUPDIR%%1"\"%2"\%datestamp%
:: Copy otl, csc, rul, rep files from App to Backup fodler
XCOPY %APPFOLDER%"\app\"%1"\"%2"\*.csc" %BACKUPDIR%%1"\"%2"\"%datestamp% /Y
XCOPY %APPFOLDER%"\app\"%1"\"%2"\*.rul" %BACKUPDIR%%1"\"%2"\"%datestamp% /Y
XCOPY %APPFOLDER%"\app\"%1"\"%2"\*.otl" %BACKUPDIR%%1"\"%2"\"%datestamp% /Y
XCOPY %APPFOLDER%"\app\"%1"\"%2"\*.rep" %BACKUPDIR%%1"\"%2"\"%datestamp% /Y
XCOPY %APPFOLDER%"\app\"%1"\"%2"\*.ind" %BACKUPDIR%%1"\"%2"\"%datestamp% /Y
cd %SCRIPTDIR%
:: Move data file from script dir to backupdir if data file exist If not exit out of code
IF NOT EXIST %SCRIPTDIR%%1"_"%2"_AllData.txt" GOTO EXIT
:END
MOVE %SCRIPTDIR%%1"_"%2"_AllData*.txt" %BACKUPDIR%%1"\"%2"\"%datestamp%
GOTO EXIT
:EXIT
exit /b
As you can see ever week a new folder is created with the creation data as its title (i.e. 102913). That folder is a subfolder of an application. I need a script to deleted the oldest folder.
So far I've tried (using test folders):
FORFILES -p "C:\Oracle\test\New folder\new folder" -s -m *.rul /D -<7> /C "cmd IF #isdir == TRUE" /c del #path
and
forfiles -p "C:\Oracle\test\New folder\new folder" -s -m *.rul /D -<7> /C "cmd /c del #path"
Any suggestion would be useful.
set "backupDir=C:\Oracle\test\New folder\new folder"
for /F "tokens=*" %%f in ('dir /ad /tc /o-d /b "%backupDir%"') do set "oldest=%backupDir%\%%f"
echo "%oldest%"
Get directory list ordered by creation date descending, only incuding directories, in brief format. Last line in list will be stored in variable %oldest% with the working directory prefixed.

Batch file to delete subfolders in directory if all files is older than 3 days

I need to complete my batch script.
I have a path C:\Users\Mahmo03S\Shaban. In that path there a several subfolders, eg. Ansys.
In the subfolder Ansys there are even more subfolders = its a foldertree.
My batch script needs to delete the Ansys folder if every files in the folder and the subfolders is older than 3 days. If just one file in Ansyn is modified in the last 3 days then nothing should happen with Ansys.
I tried to make a solid solution but:
The batch file deletes a subsubfolder in Ansys directory because the files in the subsubfolder is not modified since 3 days.
I got 3 batch files doing the task.
Script.bat
#echo off
setlocal enableextensions
pushd C:\Users\Mahmo03S\Desktop\Shaban
set /p check="Select a date:"
Rem When prompted with above line type the date 3 days ago.
forfiles /c "cmd /c (IF #isdir==TRUE call C:\Users\Mahmo03S\Desktop\Search.bat "#path" "%check%")"
popd
Search.bat
set del=TRUE
forfiles /p %1 /d -%2 /s /m * /c "cmd /c (IF #isdir ==TRUE call C:\Users\Mahmo03S\Desktop\DeleteFolders.bat "#path" "%check%" "%del%")"
DeleteFolders.bat
set del=FALSE
if %del%==FALSE (rmdir /S /Q %1)
The problem is:
I got a subsubfolder (e.g. hello) in the folder Ansys. In the hello folder every file is older than 3 days. The script deletes the hello folder which it should not do. It should only delete Ansys if EVERY file in the folder is older than 3 days. If just one file is modified in Ansys folder for the past 3 days nothing in the Ansys folder should be deleted.
I made the batch file so it deletes the Ansys folder if every file is older than 3 days. But it should not delete a subsubfolder just because the files in it is older than 3 days.
How can I do that?
A working solution can be made much simpler ;)
You can detect if FORFILES printed any result, and take action if nothing was printed.
Use FOR /D to iterate the direct child folders. For each folder, run FORFILES looking for files that are at or later than the cutoff date. If you didn't have to worry about ignoring folders, then you could simply take action based on the FORFILES return code. But you don't want to get a false positive based on a new but empty folder. You can detect if FORFILES printed any filenames using FINDSTR, and delete the folder tree if none were printed. FORFILES still prints an empty line if it finds a new folder, so you must search for a character using . instead of searching for a line using "^".
#echo off
setlocal disableDelayedExpansion
set "root=C:\Users\Mahmo03S\Shaban"
set /p "cutoff=Enter a cutoff date (mm/dd/yyyy): "
for /d %%F in ("%root%\*") do (
2>nul forfiles /p "%%F" /d %cutoff% /s /c "cmd /c if #isdir==FALSE echo #file"
) | >nul 2>nul findstr . || rd /s /q "%%F"
There are multiple methods posted on StackOverflow and elsewhere showing how to do date arithmetic in batch. I'm partial to a hybrid JScript/batch utility called getTimestamp.bat. It is pure script that runs on any modern Windows machine from XP onward - no 3rd party executable required. It is chock full of options, allowing you to do nearly any date computation you could ever imagine.
Assuming getTimestamp.bat is in your current directory, or better yet, somewhere within your PATH, then the following line can be used to compute your cutoff date instead of prompting for the date:
call gettimestamp -OD -3 -F {mm}/{dd}/{yyyy} -R cutoff
This uses a VBS script to calculate the date 3 days ago, and then checks if any files are younger than that, using xcopy, and if no files are younger than 3 days then it should remove the "C:\Users\Mahmo03S\Shaban\Ansys" folder and subdirectories.
3 days is a date calculation and not exactly 72 hours.
It's not tested.
#echo off
call :date today -3
echo mm-dd-yyyy 3 days ago was: %day%
xcopy "C:\Users\Mahmo03S\Shaban\Ansys\*.*" "%temp%\" /l /s /d:%day% |find ":" >nul
if %errorlevel% EQU 1 rd /s /q "C:\Users\Mahmo03S\Shaban\Ansys"
goto :EOF
:date
set date1=%1
set qty=%2
set separator=%~3
if /i "%date1%" EQU "TODAY" (set date1=now) else (set date1="%date1%")
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%qty%,%date1%)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^&_
echo>>"%temp%\%~n0.vbs" right(100+month(s),2)^&_
echo>>"%temp%\%~n0.vbs" right(100+day(s),2)
for /f %%a in ('cscript //nologo "%temp%\%~n0.vbs"') do set result=%%a
del "%temp%\%~n0.vbs"
endlocal& set "YY=%result:~0,4%"&set "MM=%result:~4,2%"&set "DD=%result:~6,2%"
set "day=%MM%-%DD%-%YY%"

Make subfolder names from part of file name and copy files with Robocopy

Is it posible to copy and make directories automatically from file name substrings using Robocopy?
I mean i have files like these. LAJ00306130201004626.rc the first 8 chararacters are control number (LAJ00306=control number) this would be the name of the folder and the rest are the date and time (Date=130201) (time=004626).
LAJ00306130201004626.rc
LAJ00306130202004626.rc
LAJ00306130203004626.rc
LAJ00307130201004626.rc
LAJ00307130202004626.rc
and i would like to copy and create folders from the file name like under and copy the files mentioned before in the new folders.
LAJ00306
LAJ00307
I hope to be clear if necessary ask me for more information
try this, look at the output and remove the echos before MD and ROBOCOPY, if it looks good:
#ECHO OFF &SETLOCAL ENABLEDELAYEDEXPANSION
SET "sourcefolder=."
SET "targetfolder=X:\data"
CD /d "%sourcefolder%"
FOR %%a IN (*.rc) DO (
SET "fname=%%a"
SET "folder=!fname:~0,8!"
SET "$!folder!=1"
)
FOR /f "delims=$=" %%a IN ('set "$"') DO (
ECHO MD "%targetfolder%\%%a" 2>nul
ECHO ROBOCOPY "%sourcefolder%" "%targetfolder%\%%a" "%%a*.rc"
)
Set sourcefolder and targetfolder for your folder tree.
Try this:
#echo off
pushd "c:\source folder"
setlocal enabledelayedexpansion
for %%a in (*.rc) do (
set "name=%%a"
robocopy "%cd%" "%%a" "D:\target directory\!name:~0,8!"
)
popd
Answers to your questions are:
pushd "drive:\path" makes the location the current working directory.
popd restores the last working directory
setlocal enabledelayedexpansion allows you to change and use variables within a loop, using the !variable! syntax.
If your 2000 files are in a single folder then it should work - but test it on some sample files first so that you can see how it will work.
#ECHO OFF
SETLOCAL
SET "sourcedir=."
SET "destdir=c:\destdir"
FOR /f "tokens=1*delims=_" %%i IN (
'dir /b /a-d "%sourcedir%\*_*."'
) DO XCOPY /b "%sourcedir%\%%i_%%j" "%destdir%\%%i\"
GOTO :EOF
This should accomplish the task described. You'd need to set up the source and destination directories to suit, of course. Add >nul to the end of the XCOPY line to suppress 'copied' messages.

Resources