Creating a Batch File to Move Files from Folder1 to Folder2 While Keeping the Last 3 Hours' Worth of Files in Folder1
In this article, we will discuss how to create a batch file that will move files from one folder to another, while keeping the most recent files in the original folder. This is a common task that can be useful in a variety of situations, such as freeing up space on a hard drive or organizing files in a more efficient manner.
What is a Batch File?
A batch file is a type of script file in Windows that contains a series of commands that are executed in sequence. Batch files are useful for automating repetitive tasks and can save time and effort. They are created using a text editor, such as Notepad, and saved with the extension .bat.
Creating the Batch File
To create a batch file that will move files from Folder1 to Folder2 while keeping the most recent files in Folder1, follow these steps:
- Open Notepad.
- Type the following commands, replacing "Folder1" and "Folder2" with the actual names of your folders:
@echo off
forfiles /p "Folder1" /c "cmd /c if @isdir==FALSE if @fdate >= %date:~10,4%-%date:~4,2%-%date:~7,2% echo @path" /d -3 | findstr /R /C:"[a-zA-Z]:" > keep.txt
for /f "delims=" %%a in (keep.txt) do move "%%a" "Folder2"
del keep.txt
Here's what each command does:
@echo off: This command prevents the command prompt from displaying the commands as they are executed.forfiles: This command is used to search for files that meet certain criteria. In this case, we are searching for files in Folder1 that are not directories (if @isdir==FALSE) and that were modified within the last 3 days (/d -3). We are also using the/coption to specify a command to be run on each file that is found. In this case, the command iscmd /c if @isdir==FALSE if @fdate >= %date:~10,4%-%date:~4,2%-%date:~7,2% echo @path, which checks if the file is not a directory and if its modified date is greater than or equal to the current date. If both conditions are met, the full path of the file is echoed to the console.findstr: This command is used to filter the output of the forfiles command. In this case, we are using it to only keep the lines that contain a file path (i.e., lines that start with a letter followed by a colon). The output is saved to a text file called "keep.txt".for /f: This command is used to read the contents of the "keep.txt" file and execute a command on each line. In this case, the command ismove "%%a" "Folder2", which moves the file to Folder2.del keep.txt: This command deletes the "keep.txt" file.
In this article, we have discussed how to create a batch file that will move files from one folder to another, while keeping the most recent files in the original folder. We have covered the following key concepts:
- What is a batch file?
- How to create a batch file to move files from Folder1 to Folder2 while keeping the last 3 hours' worth of files in Folder1.
- The commands used in the batch file and what they do.