Robocopy удалить файлы старше n дней
'данный скрипт удаляет в директори все файлы, у которых
'дата последней модификации старше определенного количества дней
'синтаксис таков
'killdateparam.vbs /path: /killdate: /recur:
' - папка над которой будут производиться действия
' - указывает старше скольки дней файлы будут удаляться
' - использовать или нет рекурсию
'например
'killdateparam.vbs /path:c:\0\ /killdate:8 /recur:true
'Отмечу также, что если параметры содержат пробелы,
'в нашем случае это может быть путь к папке, то его надо
'брать в кавычки
'
'ISA
'
set objNamedArgs=Wscript.Arguments.Named
'Ничего не удаляем, пока пробегаем по возвращенному набору файлов.
'Набор может быть перемешан.
'Создаём массив файловых объектов, чтобы этого избежать
on error resume next 'in case of 'in use' files.
arFiles(n).delete true
if err.number = 0 then
nDeleted = nDeleted + 1
sub SelectFiles(sPath,vKillDate,arFilesToKill,bIncludeSubFolders)
on error resume next
' добавляем файлы на удаление в массив
'
set folder = fso.getfolder(sPath)
set files = folder.files
for each file in files
' на всякий случай отслеживаем ошибки доступа к
' свойству Date
'
dtlastmodified = null
on error resume Next
dtlastmodified = file.datelastmodified
on error goto 0
if not isnull(dtlastmodified) Then
if dtlastmodified < vKillDate then
count = ubound(arFilesToKill) + 1
redim preserve arFilesToKill(count)
set arFilesToKill(count) = file
end if
end if
next
if bIncludeSubFolders then
for each fldr in folder.subfolders
SelectFiles fldr.path,vKillDate,arFilesToKill,true
next
end if
end sub
- Marked as answer by Vasily Gusev Moderator Tuesday, June 30, 2009 4:19 AM
Такой скрипт все когдато писали :-) Мои 5 коп:
Delete (or show) files older on date
name = "FileMask"
helpstring = "Files to delete. Default=*.bak"
type = "string"
required = "false"
/>
name = "DateOld"
helpstring = "Date to old (in hours). Default=72"
type = "string"
required = "false"
/>
name = "Dir"
helpstring = "Directory. Default=current"
type = "string"
required = "false"
/>
name = "DateType"
helpstring = "Date type ( [Created] | Acc[essed] | Mod[ified] | Old (by Oldes date) | New (by newes date)). Default=Created"
type = "string"
required = "false"
/>
name = "SubDir"
helpstring = "Include subdirectory. Default=no."
type = "simple"
required = "false"
/>
name = "Show"
helpstring = "Show deleted files plus show size (if need) in M,K,b. May used as simple parameter. Default=no."
type = "string"
required = "false"
/>
name = "DED"
helpstring = "Delete empty directorys. Default=no."
type = "simple"
required = "false"
/>
name = "DER"
helpstring = "Delete empty root directory. Default=no."
type = "simple"
required = "false"
/>
name = "Demo"
helpstring = "actualy not delete files (need show parameter). Default=delete."
type = "simple"
required = "false"
/>
name = "Rev"
helpstring = "Reverse. Delete files NOT old by date."
type = "simple"
required = "false"
/>
Example: DelByDate.wsf /FileMask:*.log /DateOld:24
if WScript.Arguments.Named.Item("FileMask") <> "" then
FileMask = WScript.Arguments.Named.Item("FileMask")
Else
FileMask = "*.bak"
end if
if WScript.Arguments.Named.Item("DateOld") <> "" then
DateOld = WScript.Arguments.Named.Item("DateOld")
Else
DateOld = 72
end if
if WScript.Arguments.Named.Item("Dir") <> "" then
CurDir = WScript.Arguments.Named.Item("Dir")
Else
CurDir = "."
end if
if WScript.Arguments.Named.Item("DateType") = "" then
DateType = "Created"
Elseif LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "acc" Then
DateType = "Accessed"
ElseIf LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "mod" Then
DateType = "Modified"
ElseIf LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "old" Then
DateType = "Old"
ElseIf LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "new" Then
DateType = "New"
end if
if WScript.Arguments.Named.Exists("Show") then
ShowParam = "/FileMask:" & FileMask& " /DateOld:" & DateOld & " /Dir:" & CurDir & " /DateType:" & DateType
If SubDir Then ShowParam = ShowParam & " /SubDir"
if WScript.Arguments.Named.Exists("Demo") then ShowParam = ShowParam & " /Demo"
if WScript.Arguments.Named.Exists("Rev") then ShowParam = ShowParam & " /Rev"
if WScript.Arguments.Named.Exists("DED") then ShowParam = ShowParam & " /DED"
if WScript.Arguments.Named.Exists("DER") then ShowParam = ShowParam & " /DER"
Size = ""
If LCase(WScript.Arguments.Named.Item("Show")) = "m" Then Size = ":M"
If LCase(WScript.Arguments.Named.Item("Show")) = "k" Then Size = ":K"
If LCase(WScript.Arguments.Named.Item("Show")) = "b" Then Size = ":b"
Wscript.Echo "Running parameters:" & vbcrlf & ShowParam & " /Show" & Size & vbcrlf
End If
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Global = False
' To regular file mask a'la : "*.bak" "*.lo?"
regEx.Pattern = "\."
FileMask = regEx.Replace(FileMask,"\.")
regEx.Pattern = "\?"
FileMask = regEx.Replace(FileMask,".")
regEx.Pattern = "\*"
FileMask = regEx.Replace(FileMask,".*")
If Subdir Then
Set fsoSubs=CreateObject("Scripting.FileSystemObject")
Set RootDir=fsoSubs.GetFolder(CurDir)
For each SubFold in RootDir.SubFolders
Call DelInSubFolders ( SubFold.Path, FileMask, DateOld, DateType )
Next
End if
Call DelFilesInFolder ( CurDir, FileMask, DateOld, DateType )
Set fso=CreateObject("Scripting.FileSystemObject")
Set MyDir=fso.GetFolder(CurDir)
if MyDir.Files.Count = 0 AND MyDir.SubFolders.Count = 0 AND WScript.Arguments.Named.Exists("DER") Then
If WScript.Arguments.Named.Exists("Show") Then
WScript.Echo "Delete empty root directory " & MyDir.Path
End if
if Not WScript.Arguments.Named.Exists("Demo") then MyDir.Delete (True)
End if
Sub DelInSubFolders ( Folder, FileMask, Hours, TimeType)
Set fso=CreateObject("Scripting.FileSystemObject")
Set MyDir=fso.GetFolder(Folder)
Call DelFilesInFolder ( Folder, FileMask, Hours, TimeType)
For each SubFold in MyDir.SubFolders
Call DelInSubFolders ( SubFold.Path, FileMask, Hours, TimeType)
Next
if WScript.Arguments.Named.Exists("DED") AND MyDir.Files.Count = 0 AND MyDir.SubFolders.Count = 0 Then
If WScript.Arguments.Named.Exists("Show") Then
WScript.Echo "dir - " & MyDir.Path
End if
if Not WScript.Arguments.Named.Exists("Demo") then MyDir.Delete (True)
End if
End Sub
Sub DelFilesInFolder ( Folder, FileMask, Hours, TimeType)
Set fso=CreateObject("Scripting.FileSystemObject")
Set MyDir=fso.GetFolder(Folder)
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Global = False
regEx.Pattern = FileMask
For Each DFile in MyDir.Files
If regEx.Test(DFile.Name) Then
if TimeType = "Accessed" Then
TimeToCheck = DFile.DateLastAccessed
ElseIf TimeType = "Modified" Then
TimeToCheck = DFile.DateLastModified
ElseIf TimeType = "Old" Then
TimeToCheck = DFile.DateLastModified
if TimeToCheck > DFile.DateLastAccessed Then
TimeToCheck = DFile.DateLastAccessed
End if
if TimeToCheck > DFile.DateCreated Then
TimeToCheck = DFile.DateCreated
End if
ElseIf TimeType = "New" Then
TimeToCheck = DFile.DateLastModified
if TimeToCheck < DFile.DateLastAccessed Then
TimeToCheck = DFile.DateLastAccessed
End if
if TimeToCheck < DFile.DateCreated Then
TimeToCheck = DFile.DateCreated
End if
Else
TimeToCheck = DFile.DateCreated
end If
if TimeToCheck < (now()-timeserial(Hours,0,0)) XOR WScript.Arguments.Named.Exists("Rev") Then
If WScript.Arguments.Named.Exists("Show") Then
Size = ""
If LCase(WScript.Arguments.Named.Item("Show")) = "m" Then Size = " ( " & Int(Dfile.Size/1024/10.24)/100 & " M)"
If LCase(WScript.Arguments.Named.Item("Show")) = "k" Then Size = " ( " & Int(Dfile.Size/10.24)/100 & " K)"
If LCase(WScript.Arguments.Named.Item("Show")) = "b" Then Size = " ( " & Dfile.Size & " )"
WScript.Echo "file - " & DFile.Path & Size
End if
if Not WScript.Arguments.Named.Exists("Demo") then Dfile.Delete(True)
end if
End if
Next
For example, to copy a file named yearly-report.mov from c:\reports to a file share \\marketing\videos while enabling multi-threading for higher performance (with the /mt parameter) and the ability to restart the transfer in case it's interrupted (with the /z parameter), type:
Parameters
Parameter | Description |
---|---|
Specifies the path to the source directory. | |
Specifies the path to the destination directory. | |
Specifies the file or files to be copied. Wildcard characters (* or ?) are supported. If you don't specify this parameter, *.* is used as the default value. | |
Specifies the options to use with the robocopy command, including copy, file, retry, logging, and job options. |
Copy options
- D - Data
- A - Attributes
- T - Time stamps
- S - NTFS access control list (ACL)
- O - Owner information
- U - Auditing information
- D - Data
- A - Attributes
- T - Time stamps
- R - Read only
- A - Archive
- S - System
- H - Hidden
- C - Compressed
- N - Not content indexed
- E - Encrypted
- T - Temporary
- R - Read only
- A - Archive
- S - System
- H - Hidden
- C - Compressed
- N - Not content indexed
- E - Encrypted
- T - Temporary
When using the /secfix copy option, specify the type of security information you want to copy, using one of these additional copy options:
File selection options
- R - Read only
- A - Archive
- S - System
- H - Hidden
- C - Compressed
- N - Not content indexed
- E - Encrypted
- T - Temporary
- O - Offline
- R - Read only
- A - Archive
- S - System
- H - Hidden
- C - Compressed
- N - Not content indexed
- E - Encrypted
- T - Temporary
- O - Offline
Retry options
Option | Description |
---|---|
/r: | Specifies the number of retries on failed copies. The default value of n is 1,000,000 (one million retries). |
/w: | Specifies the wait time between retries, in seconds. The default value of n is 30 (wait time 30 seconds). |
/reg | Saves the values specified in the /r and /w options as default settings in the registry. |
/tbd | Specifies that the system will wait for share names to be defined (retry error 67). |
Logging options
Option | Description |
---|---|
/l | Specifies that files are to be listed only (and not copied, deleted, or time stamped). |
/x | Reports all extra files, not just those that are selected. |
/v | Produces verbose output, and shows all skipped files. |
/ts | Includes source file time stamps in the output. |
/fp | Includes the full path names of the files in the output. |
/bytes | Prints sizes, as bytes. |
/ns | Specifies that file sizes are not to be logged. |
/nc | Specifies that file classes are not to be logged. |
/nfl | Specifies that file names are not to be logged. |
/ndl | Specifies that directory names are not to be logged. |
/np | Specifies that the progress of the copying operation (the number of files or directories copied so far) will not be displayed. |
/eta | Shows the estimated time of arrival (ETA) of the copied files. |
/log: | Writes the status output to the log file (overwrites the existing log file). |
/log+: | Writes the status output to the log file (appends the output to the existing log file). |
/unicode | Displays the status output as Unicode text. |
/unilog: | Writes the status output to the log file as Unicode text (overwrites the existing log file). |
/unilog+: | Writes the status output to the log file as Unicode text (appends the output to the existing log file). |
/tee | Writes the status output to the console window, as well as to the log file. |
/njh | Specifies that there is no job header. |
/njs | Specifies that there is no job summary. |
Job options
Option | Description |
---|---|
/job: | Specifies that parameters are to be derived from the named job file. |
/save: | Specifies that parameters are to be saved to the named job file. |
/quit | Quits after processing command line (to view parameters). |
/nosd | Indicates that no source directory is specified. |
/nodd | Indicates that no destination directory is specified. |
/if | Includes the specified files. |
Exit (return) codes
Value | Description |
---|---|
0 | No files were copied. No failure was encountered. No files were mismatched. The files already exist in the destination directory; therefore, the copy operation was skipped. |
1 | All files were copied successfully. |
2 | There are some additional files in the destination directory that are not present in the source directory. No files were copied. |
3 | Some files were copied. Additional files were present. No failure was encountered. |
5 | Some files were copied. Some files were mismatched. No failure was encountered. |
6 | Additional files and mismatched files exist. No files were copied and no failures were encountered. This means that the files already exist in the destination directory. |
7 | Files were copied, a file mismatch was present, and additional files were present. |
8 | Several files did not copy. |
Any value greater than 8 indicates that there was at least one failure during the copy operation.
Копирует данные файлов из одного расположения в другое.
Синтаксис
Например, чтобы скопировать файл с именем yearly-report.mov из c:\reports в общую папку \\marketing\videos , включив многопотоок для повышения производительности (с параметром /mt ) и возможность перезапуска передачи в случае прерывания (с параметром /z ) введите:
Параметры
Параметр | Описание |
---|---|
Указание пути к исходному каталогу. | |
Указание пути к целевому каталогу. | |
Указывает файл или файлы для копирования. Поддерживаются подстановочные знаки (* или ?). Если этот параметр не указан, *.* используется в качестве значения по умолчанию. | |
Задает параметры, используемые с командой robocopy , включая параметры копирования, файла, повторных попыток, ведения журнала и задания . |
Параметры копирования
- D — данные
- A — атрибуты
- T — метки времени
- S — список управления доступом NTFS (ACL)
- O — сведения о владельце
- U — сведения об аудите
- D — данные
- A — атрибуты
- T — метки времени
- R — только для чтения
- A — архив
- S — система
- H — скрытый
- C — сжатый
- N — не индексировано содержимое
- E — зашифровано
- T — временное
- R — только для чтения
- A — архив
- S — система
- H — скрытый
- C — сжатый
- N — не индексировано содержимое
- E — зашифровано
- T — временное
При использовании параметра копирования /secfix укажите тип сведений о безопасности, которые требуется скопировать, используя один из следующих дополнительных параметров копирования:
Параметры выбора файла
- R — только для чтения
- A - Архив
- S — система
- H — скрытый
- C — сжатый
- N — не индексировано содержимое
- E — зашифровано
- T — временный
- O — автономный режим
- R — только для чтения
- A - Архив
- S — система
- H — скрытый
- C — сжатый
- N — не индексировано содержимое
- E — зашифровано
- T — временный
- O — автономный режим
Параметры повтора
Параметр | Описание |
---|---|
/r: | Указание количества повторных попыток для неудавшихся копий. Значение по умолчанию n равно 1000 000 (один миллион повторных попыток). |
/w: | Указание времени ожидания между повторными попытками в секундах. Значение по умолчанию n равно 30 (время ожидания 30 секунд). |
/reg | Сохраняет значения, указанные в параметрах /r и /w , в качестве параметров по умолчанию в реестре. |
/tbd | Указывает, что система будет ожидать определения имен общих ресурсов (ошибка повтора 67). |
Параметры ведения журнала
Параметр | Описание |
---|---|
/l | Указывает, что файлы должны быть перечислены только (а не копируются, удаляются или метки времени). |
/x | Сообщает все дополнительные файлы, а не только выбранные. |
/v | Создает подробные выходные данные и отображает все пропущенные файлы. |
/ts | Включает метки времени исходного файла в выходные данные. |
/fp | Содержит полные имена путей файлов в выходных данных. |
/bytes | Печатает размеры в виде байтов. |
/ns | Указывает, что размеры файлов не записываются в журнал. |
/nc | Указывает, что классы файлов не записываются в журнал. |
/nfl | Указание, что имена файлов не должны регистрироваться. |
/ndl | Указание, что имена каталогов не должны регистрироваться. |
/np | Указывает, что не нужно отображать ход выполнения операции копирования (количество копируемых файлов или каталогов). |
/eta | Показывает предполагаемое время прибытия (ETA) скопированных файлов. |
/log: | Запись выходных данных о состоянии в файл журнала (перезапись существующего файла журнала). |
/log+: | Записывает выходные данные состояния в файл журнала (добавляет выходные данные в существующий файл журнала). |
/unicode | Отображает выходные данные состояния в виде текста Юникода. |
/unilog: | Записывает выходные данные состояния в файл журнала в виде текста Юникода (перезаписывает существующий файл журнала). |
/unilog+: | Записывает выходные данные состояния в файл журнала в виде текста Юникода (добавляет выходные данные в существующий файл журнала). |
/tee | Записывает выходные данные состояния в окно консоли, а также в файл журнала. |
/njh | Указывает, что заголовок задания отсутствует. |
/njs | Указывает, что сводка задания отсутствует. |
Параметры задания
Параметр | Описание |
---|---|
/job: | Указывает, что параметры должны быть производными от именованного файла задания. |
/save: | Указывает, что параметры необходимо сохранить в именованный файл задания. |
/quit | Завершает работу после обработки командной строки (для просмотра параметров). |
/nosd | Указывает, что исходный каталог не указан. |
/noddd | Указывает, что целевой каталог не указан. |
/if | Включает указанные файлы. |
Коды выхода (return)
Значение | Описание |
---|---|
0 | Файлы не были скопированы. Сбой не обнаружен. Файлы не были несовпадения. Файлы уже существуют в целевом каталоге; следовательно, операция копирования была пропущена. |
1 | Все файлы успешно скопированы. |
2 | В целевом каталоге есть несколько дополнительных файлов, которые отсутствуют в исходном каталоге. Файлы не были скопированы. |
3 | Некоторые файлы были скопированы. Были представлены дополнительные файлы. Сбой не обнаружен. |
5 | Некоторые файлы были скопированы. Некоторые файлы были несовпадения. Сбой не обнаружен. |
6 | Существуют дополнительные файлы и несовпадение файлов. Файлы не были скопированы и не обнаружены сбои. Это означает, что файлы уже существуют в целевом каталоге. |
7 | Файлы были скопированы, несогласование файлов присутствовало и были представлены дополнительные файлы. |
8 | Несколько файлов не скопируются. |
Любое значение больше 8 указывает на то, что во время операции копирования произошел по крайней мере один сбой.
I googled around and tried different things, but somehow I can't comprehend what to do here.
So I have this robocopy bat:
mkdir s:\Delete
robocopy c:\Backup\Database s:\Backup /e /MOV /LOG+:c:\robocopy.log
robocopy s:\Backup s:\Delete /e /MOV /MINAGE:14 /LOG+:c:\robocopy.log
rmdir s:\Delete /s /q
But executing this command does the following:
Creates "s:\Delete"
Moves the files from " c:\Backup\Database" to "s:\Backup"
Then deletes the ".\Database" and ".\Delete" Folder with both folders having the files.
But the ".\Database" folder gets re-created and is empty.
What am I missing?
What I want it to do:
Copy Files from a local folder to a share.
Then copy files from the share folder to a temp folder, but only files older than 14 days.
Then remove the temp folder.
Sorry if this is kind of obvious.
Contest ends 2022-05-15 Contests Complete a survey about your desktop and or gaming PC(s) Contest Details View all contests
jrp78
8 Replies
jrp78
Thank you jrp78!
That solution worked flawlessly.
I'm making a scheduled task and it's done! :)
But just to be sure, do you know why my bat file didn't work?
jrp78
I think it's because your command is saying move the contents inside the database folder, not the folder itself.
Hmm Okay.
Your solution is better either way.
MichaelMTallman
Going forward, to test any robocopy job, use the /L switch and it was run as if it was doing the job, minus moving/deleting/copying/et al. Great troubleshooting tool.
Also, I've been trying to figure out what was going wrong, with no luck. First of all, you say "copy" yet you execute a "/MOV" - are you moving the files FIRST then doing your older than 14-day operation? The only thing I can think that is happening is that your second line isn't executing right. Btw, /MOV will delete the source, since you're moving ALL the files from .\database to s:\backup, I think that is what is happening there - you're moving the folder, it might execute the delete after all files have been copied. The .\database folder probably gets recreated, I'm guessing, due to a completely different job perhaps?
Just be cautious when using /MOV and especially /MIR and /PURGE.
Thank you for the tip!
Yeah sorry for that, I basically meant "Cut/insert". :D
Yes, first move the files and then delete older than 14 days.
I just thought using /MOV will "delete" all files but not the folder.
That's the only script I use on this system and there's no other job active.
Thank you for your help!
MichaelMTallman
No problem! I've been using robocopy for two decades now and I learned about /MIR very early in that time period, luckily I didn't lose my job ;) I still use it to back up my laptop files to an external drive.
'данный скрипт удаляет в директори все файлы, у которых
'дата последней модификации старше определенного количества дней
'синтаксис таков
'killdateparam.vbs /path: /killdate: /recur:
' - папка над которой будут производиться действия
' - указывает старше скольки дней файлы будут удаляться
' - использовать или нет рекурсию
'например
'killdateparam.vbs /path:c:\0\ /killdate:8 /recur:true
'Отмечу также, что если параметры содержат пробелы,
'в нашем случае это может быть путь к папке, то его надо
'брать в кавычки
'
'ISA
'
set objNamedArgs=Wscript.Arguments.Named
'Ничего не удаляем, пока пробегаем по возвращенному набору файлов.
'Набор может быть перемешан.
'Создаём массив файловых объектов, чтобы этого избежать
on error resume next 'in case of 'in use' files.
arFiles(n).delete true
if err.number = 0 then
nDeleted = nDeleted + 1
sub SelectFiles(sPath,vKillDate,arFilesToKill,bIncludeSubFolders)
on error resume next
' добавляем файлы на удаление в массив
'
set folder = fso.getfolder(sPath)
set files = folder.files
for each file in files
' на всякий случай отслеживаем ошибки доступа к
' свойству Date
'
dtlastmodified = null
on error resume Next
dtlastmodified = file.datelastmodified
on error goto 0
if not isnull(dtlastmodified) Then
if dtlastmodified < vKillDate then
count = ubound(arFilesToKill) + 1
redim preserve arFilesToKill(count)
set arFilesToKill(count) = file
end if
end if
next
if bIncludeSubFolders then
for each fldr in folder.subfolders
SelectFiles fldr.path,vKillDate,arFilesToKill,true
next
end if
end sub
- Помечено в качестве ответа Vasily Gusev Moderator 30 июня 2009 г. 4:19
Такой скрипт все когдато писали :-) Мои 5 коп:
Delete (or show) files older on date
name = "FileMask"
helpstring = "Files to delete. Default=*.bak"
type = "string"
required = "false"
/>
name = "DateOld"
helpstring = "Date to old (in hours). Default=72"
type = "string"
required = "false"
/>
name = "Dir"
helpstring = "Directory. Default=current"
type = "string"
required = "false"
/>
name = "DateType"
helpstring = "Date type ( [Created] | Acc[essed] | Mod[ified] | Old (by Oldes date) | New (by newes date)). Default=Created"
type = "string"
required = "false"
/>
name = "SubDir"
helpstring = "Include subdirectory. Default=no."
type = "simple"
required = "false"
/>
name = "Show"
helpstring = "Show deleted files plus show size (if need) in M,K,b. May used as simple parameter. Default=no."
type = "string"
required = "false"
/>
name = "DED"
helpstring = "Delete empty directorys. Default=no."
type = "simple"
required = "false"
/>
name = "DER"
helpstring = "Delete empty root directory. Default=no."
type = "simple"
required = "false"
/>
name = "Demo"
helpstring = "actualy not delete files (need show parameter). Default=delete."
type = "simple"
required = "false"
/>
name = "Rev"
helpstring = "Reverse. Delete files NOT old by date."
type = "simple"
required = "false"
/>
Example: DelByDate.wsf /FileMask:*.log /DateOld:24
if WScript.Arguments.Named.Item("FileMask") <> "" then
FileMask = WScript.Arguments.Named.Item("FileMask")
Else
FileMask = "*.bak"
end if
if WScript.Arguments.Named.Item("DateOld") <> "" then
DateOld = WScript.Arguments.Named.Item("DateOld")
Else
DateOld = 72
end if
if WScript.Arguments.Named.Item("Dir") <> "" then
CurDir = WScript.Arguments.Named.Item("Dir")
Else
CurDir = "."
end if
if WScript.Arguments.Named.Item("DateType") = "" then
DateType = "Created"
Elseif LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "acc" Then
DateType = "Accessed"
ElseIf LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "mod" Then
DateType = "Modified"
ElseIf LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "old" Then
DateType = "Old"
ElseIf LCase(Mid(WScript.Arguments.Named.Item("DateType"),1,3)) = "new" Then
DateType = "New"
end if
if WScript.Arguments.Named.Exists("Show") then
ShowParam = "/FileMask:" & FileMask& " /DateOld:" & DateOld & " /Dir:" & CurDir & " /DateType:" & DateType
If SubDir Then ShowParam = ShowParam & " /SubDir"
if WScript.Arguments.Named.Exists("Demo") then ShowParam = ShowParam & " /Demo"
if WScript.Arguments.Named.Exists("Rev") then ShowParam = ShowParam & " /Rev"
if WScript.Arguments.Named.Exists("DED") then ShowParam = ShowParam & " /DED"
if WScript.Arguments.Named.Exists("DER") then ShowParam = ShowParam & " /DER"
Size = ""
If LCase(WScript.Arguments.Named.Item("Show")) = "m" Then Size = ":M"
If LCase(WScript.Arguments.Named.Item("Show")) = "k" Then Size = ":K"
If LCase(WScript.Arguments.Named.Item("Show")) = "b" Then Size = ":b"
Wscript.Echo "Running parameters:" & vbcrlf & ShowParam & " /Show" & Size & vbcrlf
End If
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Global = False
' To regular file mask a'la : "*.bak" "*.lo?"
regEx.Pattern = "\."
FileMask = regEx.Replace(FileMask,"\.")
regEx.Pattern = "\?"
FileMask = regEx.Replace(FileMask,".")
regEx.Pattern = "\*"
FileMask = regEx.Replace(FileMask,".*")
If Subdir Then
Set fsoSubs=CreateObject("Scripting.FileSystemObject")
Set RootDir=fsoSubs.GetFolder(CurDir)
For each SubFold in RootDir.SubFolders
Call DelInSubFolders ( SubFold.Path, FileMask, DateOld, DateType )
Next
End if
Call DelFilesInFolder ( CurDir, FileMask, DateOld, DateType )
Set fso=CreateObject("Scripting.FileSystemObject")
Set MyDir=fso.GetFolder(CurDir)
if MyDir.Files.Count = 0 AND MyDir.SubFolders.Count = 0 AND WScript.Arguments.Named.Exists("DER") Then
If WScript.Arguments.Named.Exists("Show") Then
WScript.Echo "Delete empty root directory " & MyDir.Path
End if
if Not WScript.Arguments.Named.Exists("Demo") then MyDir.Delete (True)
End if
Sub DelInSubFolders ( Folder, FileMask, Hours, TimeType)
Set fso=CreateObject("Scripting.FileSystemObject")
Set MyDir=fso.GetFolder(Folder)
Call DelFilesInFolder ( Folder, FileMask, Hours, TimeType)
For each SubFold in MyDir.SubFolders
Call DelInSubFolders ( SubFold.Path, FileMask, Hours, TimeType)
Next
if WScript.Arguments.Named.Exists("DED") AND MyDir.Files.Count = 0 AND MyDir.SubFolders.Count = 0 Then
If WScript.Arguments.Named.Exists("Show") Then
WScript.Echo "dir - " & MyDir.Path
End if
if Not WScript.Arguments.Named.Exists("Demo") then MyDir.Delete (True)
End if
End Sub
Sub DelFilesInFolder ( Folder, FileMask, Hours, TimeType)
Set fso=CreateObject("Scripting.FileSystemObject")
Set MyDir=fso.GetFolder(Folder)
Set regEx = New RegExp
regEx.IgnoreCase = True
regEx.Global = False
regEx.Pattern = FileMask
For Each DFile in MyDir.Files
If regEx.Test(DFile.Name) Then
if TimeType = "Accessed" Then
TimeToCheck = DFile.DateLastAccessed
ElseIf TimeType = "Modified" Then
TimeToCheck = DFile.DateLastModified
ElseIf TimeType = "Old" Then
TimeToCheck = DFile.DateLastModified
if TimeToCheck > DFile.DateLastAccessed Then
TimeToCheck = DFile.DateLastAccessed
End if
if TimeToCheck > DFile.DateCreated Then
TimeToCheck = DFile.DateCreated
End if
ElseIf TimeType = "New" Then
TimeToCheck = DFile.DateLastModified
if TimeToCheck < DFile.DateLastAccessed Then
TimeToCheck = DFile.DateLastAccessed
End if
if TimeToCheck < DFile.DateCreated Then
TimeToCheck = DFile.DateCreated
End if
Else
TimeToCheck = DFile.DateCreated
end If
if TimeToCheck < (now()-timeserial(Hours,0,0)) XOR WScript.Arguments.Named.Exists("Rev") Then
If WScript.Arguments.Named.Exists("Show") Then
Size = ""
If LCase(WScript.Arguments.Named.Item("Show")) = "m" Then Size = " ( " & Int(Dfile.Size/1024/10.24)/100 & " M)"
If LCase(WScript.Arguments.Named.Item("Show")) = "k" Then Size = " ( " & Int(Dfile.Size/10.24)/100 & " K)"
If LCase(WScript.Arguments.Named.Item("Show")) = "b" Then Size = " ( " & Dfile.Size & " )"
WScript.Echo "file - " & DFile.Path & Size
End if
if Not WScript.Arguments.Named.Exists("Demo") then Dfile.Delete(True)
end if
End if
Next
Читайте также: