Лучший отвечающий
Скрипт очистки папки обмена файлами

Вопрос
-
Коллеги, помогите отладить скрипт. При запуске скрипт не отрабатывает, ошибок не выдает.
'========================================================================== On Error Resume Next '================================ 'предварительная инициализация '================================ Set args = WScript.Arguments if args.Count = 0 Then WScript.Echo "Usage: [CScript | WScript] clear_exchange.vbs <exchangefolderspoint>" WScript.Quit 1 end if '================================ 'определение глобальных значений '================================ ExchangeFoldersPoint = args.Item("D:\Distr") 'Основная папка обмена DeletionQueueFolderName = "_deletion_queue_" 'папка для хранения файлов стоящие в очереди удаления LeaveOutFolders = Array("") 'не удаляемые папки SkipedFiles = Array("exchange_folder_information.txt") 'пропускать файлы внутри папки обмена (exchange_folder_information.txt - список файлов) SkipedFolders = Array (DeletionQueueFolderName, "donotdelete")'пропускать папки внутри папки обмена 'DeletionQueueFolderName должны постоянно быть в этом списке DeletionQueueDaysOld = 2 'прошло дней с последней модификации файла .удалить ExchangeDaysOld = 1 'прошло дней с последней модификации файла .переместить в очередь удаления '================================ ' functions library '================================ '----common functions----- Function InArray(Arr, SearchIt) arr_temp = Filter(Arr, SearchIT, True, 1) InArray = false For Each element In arr_temp If UCase(element) = UCase(SearchIt) Then InArray = true Next End Function Function FixAp(body) FixAp=Replace(body, "'", "\'") End Function '----files and folders operations---- Function DeleteFolder(Folderpath) DeleteFolder = 53 Set colFolders = objWMIService.ExecQuery("Select * from Win32_Directory where Name = '" & FixAp(Replace(Folderpath, "\", "\\")) & "'") For Each objFolder in colFolders errResults = objFolder.Delete Next DeleteFolder = errResult 'objFSO.DeleteFolder(Folderpath) End Function Function MoveFolder(SourcePath, DestinationPath, Foldername) MoveFolder = 53 Set colFolders = objWMIService.ExecQuery("Select * from Win32_Directory where Name = '" & FixAp(Replace(SourcePath & "\" & Foldername, "\", "\\")) &"'") For Each objFolder in colFolders errResults = objFolder.Rename(DestinationPath & "\" & Foldername) Next MoveFolder = errResults End Function Function DeleteFile(Filepath) DeleteFile = 53 Set colFiles = objWMIService.ExecQuery("Select * from CIM_Datafile where Name = '" & FixAp(Replace(Filepath, "\", "\\")) & "'") For Each objFile in colFiles errResults = objFile.Delete Next DeleteFile = errResults End Function Function MoveFile(SourcePath, DestinationPath, Filename) MoveFile = 53 Set colFiles = objWMIService.ExecQuery("Select * from CIM_Datafile where Name = '" & FixAp(Replace(SourcePath & "\" & Filename, "\", "\\")) & "'") For Each objFile in colFiles errResults = objFile.Rename(DestinationPath & "\" & Filename) Next MoveFile = errResult End Function Function DeleteFolders(SourcePath, ExcludedDirs) Set objFolder = objFSO.GetFolder(SourcePath) Set colSubfolders = objFolder.Subfolders For Each objSubfolder in colSubfolders If Not InArray(ExcludedDirs, objSubfolder.Name) Then DeleteFolder(SourcePath & "\" & objSubfolder.Name) Next End Function Function MoveFolders(SourcePath, DestinationPath, ExcludedDirs) Set objFolder = objFSO.GetFolder(SourcePath) Set colSubfolders = objFolder.Subfolders For Each objSubfolder in colSubfolders If Not InArray(ExcludedDirs, objSubfolder.Name) Then MoveFolder SourcePath, DestinationPath, objSubfolder.Name Next End Function Function DeleteFiles(SourcePath, ExcludedFiles) Set Folder = objFSO.GetFolder(SourcePath) For Each file In Folder.Files If Not InArray(ExcludedFiles, Mid(file, Len(SourcePath)+2)) Then DeleteFile(file) Next End Function Function MoveFiles(SourcePath, DestinationPath, ExcludedFiles) Set Folder = objFSO.GetFolder(SourcePath) For Each file In Folder.Files If Not InArray(ExcludedFiles, Mid(file, Len(SourcePath)+2)) Then MoveFile SourcePath, DestinationPath, Mid(file, Len(SourcePath)+2) Next End Function '================================ 'инициализация '================================ strComputer = "." Set objFSO = CreateObject("Scripting.FileSystemObject") Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") '================================ 'обработка '================================ Function deleteOldFiles(Folderpath, DaysOld) 'first processing all subfolders deleteOldFiles = False For Each Subfolder In objFSO.GetFolder(Folderpath).SubFolders sPath = Subfolder.Path If Not deleteOldFiles(Subfolder.Path, DaysOld) Then DeleteFolder sPath Else deleteOldFiles = True End If Next 'next proccessing old files For Each File In objFSO.GetFolder(Folderpath).Files If File.DateLastModified < (Date() - DaysOld) Then If DeleteFile(File) Then deleteOldFiles = True Else deleteOldFiles = True End If Next End Function filesIsMoved = 0 Function moveOldFiles(Folderpath, DaysOld, ExcludedFolders, ExcludedFiles) 'first processing all subfolders moveOldFiles = 1 For Each Subfolder In objFSO.GetFolder(Folderpath).SubFolders sPath = Subfolder.Path If Not InArray(ExcludedFolders, Subfolder.Name) Then If moveOldFiles(Subfolder.Path, DaysOld, ExcludedFolders, ExcludedFiles) Then DeleteFolder sPath Else moveOldFiles = 0 End If Else moveOldFiles = 0 End If Next 'next proccessing old files structureCreated = False curFolder = Mid(FolderPath, Len(ExchangeFoldersPoint) + 2) curDFolder = ExchangeFoldersPoint + "\" + DeletionQueueFolderName + "\" + curFolder For Each File In objFSO.GetFolder(Folderpath).Files If Not InArray(ExcludedFiles, Mid(file, Len(Folderpath)+2)) And File.DateLastModified < (Date() - DaysOld) Then If Not structureCreated Then If Not objFSO.FolderExists(curDFolder) Then tArr = Split(curFolder, "\") cDir = "" For Each DirName In tArr If cDir = "" Then cDir = DirName Else cDir = cDir & "\" & DirName End If tDir = ExchangeFoldersPoint + "\" + DeletionQueueFolderName + "\" & cDir If Not objFSO.FolderExists(tDir) Then objFSO.CreateFolder(tDir) Next End If structureCreated = 1 End If MoveFile FolderPath, curDFolder, Mid(File, Len(FolderPath)+2) Else moveOldFiles = 0 End If Next End Function Function ProcessExchangeFolder(Folderpath) 'checking existing deletion queue folder and creating it on necessary If not objFSO.FolderExists(Folderpath & "\" & DeletionQueueFolderName) Then objFSO.CreateFolder(Folderpath & "\" & DeletionQueueFolderName) Else deleteOldFiles Folderpath & "\" & DeletionQueueFolderName, DeletionQueueDaysOld End If moveOldFiles Folderpath, ExchangeDaysOld, SkipedFolders, SkipedFiles End Function 'For Each Subfolder in objFSO.GetFolder(ExchangeFoldersPoint).SubFolders ' If not InArray(LeaveOutFolders, Subfolder.Name) Then ' currentExchangeFolder = Subfolder.Name ' ProcessExchangeFolder(Subfolder.Path) ' End If 'Next ProcessExchangeFolder(ExchangeFoldersPoint)
12 апреля 2012 г. 11:10
Ответы
-
Может лучше PS использовать?
Вот пример скрипта, который чистит шару для обмена данными м\у юзерами
Param ( $Path = "\\ServerName\Commonplace", $AgeOfFiles = 14 ) # Удаляем файлы, которые не использовались больше 14 дней от текущей даты. $Date = get-date -uformat "%d.%m.%Y" Get-ChildItem -Path "$Path\*" -Recurse -Force | Where-Object {$_.PSIsContainer -eq $false -and $_.LastWriteTime -lt ((get-date).date).AddDays(-$AgeOfFiles)} | %{Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue} # Удаляем пустые подпапки в структуре. Get-ChildItem -Path "$Path\*" -Recurse -Force | Where-Object {$_.PSIsContainer -eq $true} | % {if((Get-ChildItem -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).sum -eq $null){ Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue} } <# Удаляем пустые папки в корне ресурса. Get-ChildItem -Path $Path -Force | Where-Object {$_.PSIsContainer -eq $true} | % {if((Get-ChildItem -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).sum -eq $null){ Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue} } #>
Его можно дописать, модернизировать под ваши нужды.
- Предложено в качестве ответа Angel-Keeper 13 апреля 2012 г. 6:55
- Помечено в качестве ответа Виктор Мольбо 17 апреля 2012 г. 9:58
13 апреля 2012 г. 5:28
Все ответы
-
Может обычная утилита robocopy вас устроит? С ней практически тоже самое можно сделать.
Сазонов Илья http://isazonov.wordpress.com/
12 апреля 2012 г. 13:20Модератор -
Может лучше PS использовать?
Вот пример скрипта, который чистит шару для обмена данными м\у юзерами
Param ( $Path = "\\ServerName\Commonplace", $AgeOfFiles = 14 ) # Удаляем файлы, которые не использовались больше 14 дней от текущей даты. $Date = get-date -uformat "%d.%m.%Y" Get-ChildItem -Path "$Path\*" -Recurse -Force | Where-Object {$_.PSIsContainer -eq $false -and $_.LastWriteTime -lt ((get-date).date).AddDays(-$AgeOfFiles)} | %{Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue} # Удаляем пустые подпапки в структуре. Get-ChildItem -Path "$Path\*" -Recurse -Force | Where-Object {$_.PSIsContainer -eq $true} | % {if((Get-ChildItem -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).sum -eq $null){ Remove-Item $_.FullName -Recurse -Force -ErrorAction SilentlyContinue} } <# Удаляем пустые папки в корне ресурса. Get-ChildItem -Path $Path -Force | Where-Object {$_.PSIsContainer -eq $true} | % {if((Get-ChildItem -Path $_.FullName -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).sum -eq $null){ Remove-Item $_.FullName -Force -ErrorAction SilentlyContinue} } #>
Его можно дописать, модернизировать под ваши нужды.
- Предложено в качестве ответа Angel-Keeper 13 апреля 2012 г. 6:55
- Помечено в качестве ответа Виктор Мольбо 17 апреля 2012 г. 9:58
13 апреля 2012 г. 5:28 -
pushd D:\TEMP && rd /s /q . > nul 2>&1
Вот мой вариант =)
Сначала Вас игнорируют, потом над Вами смеются, потом с Вами борются, а затем Вы победили.
27 мая 2012 г. 8:25