Уровень сложностиСредний
Время на прочтение2 мин
Количество просмотров5.8K
Одной из наверное классических задач системного администратора является организация общей шары (файлопомойки), для оперативного обмена данными между сотрудниками.
Одной из проблем является то что этот «Обменник» превращается в инструмент долговременного хранения файлов, что недопустимо. посему всем сотрудникам сообщаем, что данные будут регулярно удаляться через N дней после их размещения на шаре.
А сами вооружаемся powershell и task scheduler, создаем скрипт со следующим содержимым и в планировщике ставим его на ежедневное исполнение
#Дата с которой сравнивать. В этом случае -15 дней от текущей даты
$date = (Get-Date).AddDays(-15)
#Путь до директории откуда удалять файлы
$path = "d:\data\public"
#Расположение отчетов
$report = "C:\scripts\Result\file_list.txt"
#Работаем с файлами
#Вывод спписка всех файлов без папок (в т.ч. внутри папок) старше чем значение в $date
$filelist = Get-ChildItem -Recurse -Path $path -file | Where-Object -Property CreationTime -lT $date
$filelist | Sort-Object -Property CreationTime | ft CreationTime ,VersionInfo | tee $report
#Удаляем файлы
#$filelist | Remove-Item
#Работаем с каталогами
#вывод списка пустых директорий(где нет ни файлов ни директорий) старше чем дата $date
$folderlist = Get-ChildItem -Recurse -Path $path -Directory | Where-Object -Property LastWriteTime -lT $date | where { $_.psiscontainer -eq $true -and $_.GetFiles().count -eq 0 -and $_.GetDirectories().count -eq 0 }
#вывод списка пустых директорий (где нет файлов, но есть директории) старше чем дата $date
#$folderlist = Get-ChildItem -Recurse -Path $path -Directory | Where-Object -Property LastWriteTime -lT $date | where { $_.psiscontainer -eq $true -and $_.GetFiles().count -eq 0 }
$folderlist | Sort-Object -Property LastWriteTime | ft LastWriteTime ,FullName | tee $report -Append
#Удаляем каталоги
#$folderlist | Remove-Item
P.s чукча не писатель и не великий кодер, пишу как умею
Ссылка на гит https://github.com/fiverok/psscripts/blob/main/Del_old_files.ps1
+2
Комментарии16
Want to delete the pictures you saved a few days ago? Or, perhaps you want to remove the files you downloaded last week.
Whatever the case may be, we’ve got you covered. In this article, we’ll explore different ways to delete files from a specific date, be it a day, a week, a month, or even a year ago.
1. Use File Explorer
There’s no denying that File Explorer is one of the best file management tools for Windows. So, let’s check out how this tool can help you delete specific files:
- Press Win + E to open File Explorer.
- Navigate to the folder containing your files. In this example, we’ll navigate to the Downloads folder.
- Type datemodified: in the File Explorer search bar. This should display the «Search» tab in the top-left corner.
- Scroll to the Search tab, click the Date modified drop-down menu, and then select your preferred option.
Finally, select the files you don’t need and then press the Delete key.
Alternatively, you can search for your files using a specific date. For example, here’s how to search for files that were modified on a certain day:
- Navigate to the folder containing the files you want to delete.
- Type datemodified:28/08/2022 in the File Explorer search bar. However, replace “28/08/2022” with your preferred date.
Finally, select and delete the files you don’t need.
To pick a date range, follow these steps:
- Open the folder containing the files you want to delete.
- Type datemodified:28/08/2022 .. 31/08/2022 in the File Explorer search bar, but replace “28/08/2022 .. 31/08/2022” with your preferred date range.
- Select the relevant files and delete them.
To search for your files based on the date they were created, follow these steps:
- Navigate to the folder containing your files.
- Type datecreated:22/09/2022 in the File Explorer search bar, but replace “22/09/2022” with your preferred date.
To pick a date range for the “date created” option, follow these steps:
- Open the target folder containing your files.
- Type datecreated:15/09/2022 .. 22/09/2022 and replace “15/09/2022 .. 22/09/2022” with your preferred date range.
- Select the relevant files and delete them.
2. Use the Command Prompt
The Command Prompt is a powerful tool that you can use for various purposes. For example, you can use it to tweak the system settings or run various apps.
Interestingly, the Command Prompt can also help you remove files on Windows. So, let’s see how you can delete your old files using this tool:
- Type Command Prompt in the Start menu search bar.
- Right-click on the Best match result and select Run as administrator.
- Type the following command:
ForFiles /p "C:\Target_Folder" /s /d -Number_of_Days /c "cmd /c del @file"
Replace the C:\Target_Folder with the correct folder path. From there, replace the Number_of_Days command with the number of days in which the files were last modified.
Here’s how you can find your folder path:
- Press Win + E to open File Explorer.
- Navigate to the folder containing the files you want to delete. In this example, we’ll navigate to the Downloads folder.
- Type CMD in File Explorer’s address bar and press Enter. This should open a Command Prompt window.
- Select the folder path displayed and press Ctrl + C to copy it. In this example, the folder path is C:\Users\tladi\Downloads.
You now have your folder path.
So, you can now decide on the files you want to delete. For example, let’s say you pick files that were last modified 14 days ago.
With all the details you currently have, here’s what your command should look like:
ForFiles /p "C:\Users\tladi\Downloads" /s /d -14 /c "cmd /c del @file"
After entering all the details in your command, press Enter to start deleting your files.
3. Use the Task Scheduler
You can also delete your files by using the Task Scheduler. Here are the steps you need to follow:
- Type Task Scheduler in the Start menu search bar and select the Best match.
- Right-click on the Task Scheduler Library option in the top-left corner and select New Folder.
- Name the folder as Delete Old Files or something similar.
- Press OK to save these changes.
Right-click on the Delete Old Files folder and select Create Task. This should take you to the «General» tab on the «Create Task» window.
Specify the task name in the «Name» box. For example, you can name the task as Delete Old Files in the Downloads Folder.
From there, scroll down and select the Run whether user is logged on or not option. Next, click the Configure for drop-down menu and select the relevant option.
From there, scroll to the Triggers tab and press the New button at the bottom. This should display the «New Trigger» window.
Follow these steps once you’re on the “New Trigger” window:
- Click the Begin the task drop-down menu and select On a schedule.
- Select whether you want to run the task once, daily, weekly, or monthly by picking the relevant option in the top-left corner.
- Press OK to save these changes. This should take you back to the «Triggers» tab.
Navigate to the Actions tab and press the New button at the bottom. This should display the “New Action” window.
Follow these steps when you’re on the “New Action” window:
- Type ForFiles.exe in the Program/script box.
- Type the following command in the Add arguments box:
/p "%userprofile%\Target_Folder" /s /d -Number_of_Days /c "cmd /c del @file"
Replace the Number_of_Days command with the number of days in which the files were last modified. For example, you can pick 21 if you want files that were last modified three weeks ago.
From there, replace the Target_Folder command with the correct folder path. For example, if your original folder path is C:\Users\tladi\Downloads, then you should replace Target_Folder with Users\tladi\Downloads.
By now, you have all the information you need. So, you should have ForFiles.exe in the «Program/script» box and the following command in the «Add arguments» section:
/p "%userprofile%\Users\tladi\Downloads" /s /d -21 /c "cmd /c del @file"
Press the OK button after entering the details.
Now, your files should be deleted automatically using the task you’ve created. To get rid of this task at a later stage, open the Task Scheduler and remove the Delete Old Files folder.
4. Use the System Settings
Want to automatically delete old files from the Recycle Bin or the Downloads folder? The system settings can help.
Here are the steps you need to follow:
- Type Settings in the Start menu search bar and select the Best match.
- Select System from the options.
- Click Storage on the left and then select Configure Storage Sense or run it now on the right-hand side.
- Click the Delete files in my Downloads folder if they haven’t been opened for more than drop-down menu.
- Select 1, 14, 30, or 60 days from the options.
Next, click the Delete files in my Recycle Bin if they have been there for drop-down menu and configure the settings to your liking.
Finally, close the settings windows and restart your device to save these changes.
Delete Any File on Your Windows Device, Hassle-Free
Deleting files on Windows is quite easy. But sometimes, you just want to delete files using a specific date range.
So, if you need to delete files older than a certain number of days, try the solutions we’ve covered. And if those files refuse to leave your device, there are solutions for that too.
Удаление файлов через cmd утилитой forfiles.exe
Пример как с ее помощью можно удалять бекапы старше 20 дней:
forfiles.exe /p С:\Backup\ /s /m *.* /d -20 /c “cmd /c del /q /f @file”
обычный батник – и вуаля само делает неинтересную работу..
справка по FORFILES
FORFILES [/P <путь>] [/M <маска_поиска>] [/S]
[/C <команда>] [/D [+ | -] {dd.MM.yyyy | dd}]
Описание.
Выбор файла (или набора файлов) и выполнение команды
с этим файлом. Программа полезна для пакетных заданий.
Параметры:
/P <путь> Путь, с которого начинается поиск.
По умолчанию используется текущая
рабочая папка (.).
/M <маска_поиска> Поиск файлов с помощью маски.
Маска поиска по умолчанию “*” .
/S Рекурсивное выполнение программы forfiles
во всех подпапках, аналогично “DIR /S”.
/C <команда> Команда, которая выполняется для каждого файла.
Строки команд необходимо заключать в прямые
кавычки.
Команда по умолчанию “cmd /c echo @file”.
Следующие переменные могут использоваться
в строке команды:
@file – возвращает имя файла.
@fname – возвращает имя файла без
расширения.
@ext – возвращает только расширение имени
файла.
@path – возвращает полный путь к файлу.
@relpath – возвращает относительный путь к
файлу.
@isdir – возвращает значение “TRUE”, если типом
файла является папка, и “FALSE” для файлов.
@fsize – возвращает размер файла
в байтах.
@fdate – возвращает дату последнего изменения
файла.
@ftime – возвращает время последнего изменения
файла.
Для включения специальных символов в строку команды
следует использовать шестнадцатеричный код символа
в формате 0xHH (например, 0x09 для табуляции).
Перед внутренними командами CMD.exe необходимо ставить
“cmd /c”.
/D <дата> Выбор файлов, у которых дата последнего изменения
больше или равна (+) либо меньше или равна
(-) указанной дате при использовании формата
“dd.MM.yyyy”; либо файлов, у которых дата последнего
изменения больше или равна (+)
текущей дате плюс “dd” дней либо меньше или
равна (-) текущей дате минус “dd” дней.
Допустимым числом дней “dd” является любое
число в диапазоне 0 – 32768.
“+” используется по умолчанию, если знак не указан.
/? Вывод справки по использованию.
Примеры:
FORFILES /?
FORFILES
FORFILES /P C:\WINDOWS /S /M DNS*.*
FORFILES /S /M *.txt /C “cmd /c type @file | more”
FORFILES /P C:\ /S /M *.bat
FORFILES /D -30 /M *.exe
/C “cmd /c echo @path 0x09 был изменен 30 дней назад”
FORFILES /D 01.01.2001
/C “cmd /c echo @fname является новым с 1-янв-2001”
FORFILES /D +25.1.2011 /C “cmd /c echo @fname является новым сегодня”
FORFILES /M *.exe /D +1
FORFILES /S /M *.doc /C “cmd /c echo @fsize”
FORFILES /M *.txt /C “cmd /c if @isdir==FALSE notepad.exe @file”
Windows 10 has a number of improvements that allow you to keep your PC clean. Its recent versions include built-in tools to automatically empty the Recycle Bin and clean the Downloads folder periodically. Unfortunately, if you are running an early build of Windows 10 or a previous version of the OS, these features are not available for you. Here is how you can delete files older than certain days using three different methods.
To achieve this goal, you don’t even need any third-party tools. This can be done using either File Explorer, PowerShell or a batch file.
File Explorer is the default file manager app in Windows 10. It has a special search box. When it gets focused, it shows a number of advanced options in the Ribbon. To activate the search feature in File Explorer, click on the search box or press F3 on the keyboard. The Ribbon will then look as follows:
Here is how to use it to delete files older than a certain number of days.
Delete Files Older Than X Days with File Explorer
- Open the Search tools tab in the Ribbon (F3).
- Click on the Date modified button. It has a drop down list with options.
- Select the desired option, like Last week.
File Explorer will filter the results immediately. Select the files you don’t need, and press the Delete key to delete files. Alternatively, you can right-click the selection and choose Delete from the context menu.
Tip: You can use your own, custom size filters. All you need is to type the desired filter condition in the search box of File Explorer as follows:
datemodified:11/1/2017 .. 11/20/2017
Instead of ‘datemodified’, you could use ‘datecreated’ to find files in a specific date range.
Alternatively, you can type the date related parameter and enter a colon character (:). This will make File Explorer show the date picker. Pick a date or condition from the calendar pop-up. You can click on a date and drag to specify a date range. This way you can filter the results to get exactly what you want.
This method is good for deleting files manually once in a while. If you need to automate the procedure, e.g. clean up the Downloads folder on a periodic basis, you should use either the command prompt or PowerShell methods. Let’s review them.
Delete Files Older Than X Days with a Batch File
In my previous article, Find Large Files in Windows 10 Without Third-Party Tools, we have learned about the useful ForFiles console command. This command selects a file (or a set of files) and executes a command on that file.
The switches we can use are as follows:
/S — This switch makes forfiles recurse subdirectories. Like «DIR /S».
/D — Select files with a last modified date. For example,-365 means over a year ago, -30 means a month ago.
/P — To indicate the path to start the search.
/C «command» — This command specifies the command to execute on each file that will be found. Command strings should be wrapped in double quotes.
The default command is «cmd /c echo @file».
The following variables can be used in the command string:
@file — returns the name of the file.
@fname — returns the file name without extension.
@ext — returns only the extension of the file.
@path — returns the full path of the file.
@relpath — returns the relative path of the file.
@isdir — returns «TRUE» if a file type is
a directory, and «FALSE» for files.
@fsize — returns the size of the file in bytes.
@fdate — returns the last modified date of the file.
@ftime — returns the last modified time of the file.
To delete files older that X days, do the following.
- Open a new command prompt instance.
- Type the following command:
ForFiles /p "C:\My Folder" /s /d -30 /c "cmd /c del @file"
Substitute the folder path and the amount of days with desired values and you are done.
For example, to remove the files older than a month from the Downloads folder, use the following command:
ForFiles /p "%userprofile%\Downloads" /s /d -30 /c "cmd /c del @file"
This trick works in all modern versions of Windows including Windows 7, Windows 8, Windows 8.1 and Windows 10.
Delete Files Older Than X Days Automatically
You can automate this task using the built-in Task Scheduler app.
- Open Administrative tools and click on the Task Scheduler icon.
- In the left pane, click the item «Task Scheduler Library»:
- In the right pane, click on the link «Create task»:
- A new window titled «Create Task» will be opened. On the «General» tab, specify the name of the task. Pick an easily recognizable name like «Delete Old Files».
- Switch to the «Actions» tab. There, click the «New…» button:
- The «New Action» window will be opened. There, you need to specify the following data.
Action: Start a program
Program/script:ForFiles.exe
Add arguments(optional):/p "%userprofile%\Downloads" /s /d -30 /c "cmd /c del @file"
Change the folder path and the number of days to what you need.
- Go to the Triggers tab in your task. There, click on the New button.
- Under Begin the task, select «On a schedule» in the drop down list and click the OK button. Specify when you want the task to run.
- Switch to the «Settings» tab. Enable the options
— Allow task to be run on demand.
— Run task as soon as possible after a scheduled start missed. - Click OK to create your task.
That’s it.
Finally, if your prefer PowerShell, you can use a special cmdlet to remove old files.
Delete Files Older Than X Days with PowerShell
- Open a new PowerShell window.
- Type the following command:
Get-ChildItem "%userprofile%\Downloads" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))}| Remove-Item
If the Get-ChildItem cmdlet finds any files that are older than a month, then the Remove-Item cmdlet will be called for each file to remove it.
That’s it.
Support us
Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:
If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!
Индивидуальный подход
Доверительные партнерские отношения, подробное изучение сферы деятельности клиентов, особенностей организации их работы позволяют нам четко определять необходимые тактические и стратегические задачи, что поднимает наших партнеров на более высокий уровень среди конкурентов.
Подробнее
Гарантия качеcтва
Выполнение поставленных задач в максимально короткие сроки. Надежность и высокий профессионализм. «Прозрачная» ценовая политика. Предоставление любой информации клиенту, касающейся текущей работы и расходов. Мы полностью отвечаем за качество выполненных работ и соответствие вашим желаниям.
Подробнее
Решение задач любой сложности
Для нас нет ничего невозможного! Реализация любых целей по оригинальным проектам. Все работы выполняются квалифицированными специалистами, регулярно проходящими плановое обучение и аттестацию.
Подробнее
7 июля 2015
Создаем обычный .bat файл, сделать это можно с помощью блокнота.
Вписываем туда команду
Forfiles -p «C:\папка с файлами» -s -m *.* -d -60 -c «cmd /c del /q @path»
Параметры
-p папка в которой мы будем удалять файлы
-s рекурсивное удаление (удаление во всех папках и под папках)
-m маска поиска файлов
-d (количество дней) выбор файлов, у которых дата изменения меньше или равна (-) текущей даты.
-с команда, которая выполняется для каждого файла
del — команда удаления
/q — отключения запросов на подтверждение при удалении
@path — возвращает полный путь до файла.
Сохраняем файл с расширением .bat
Удаление файлов по сети с помощью forfiles