DavidLago Posted July 6, 2011 Share Posted July 6, 2011 Hello people! I'm a beginner in the world of AutoIt Scripting, so, don't be alarmed if you see something that could be done in a much more simple way than I did, that is due to my lack of experience I work at a company, as a Server support analyst, and once in a while me and my team see ourselves needing some Scripts for repetitive tasks and such. I got several ones to do (there is a huge list) and some of them are already done, but they were made for coorporative applications and won't be useful to anyone. But this one and some other ones are. I'll be posting them here gradually. This Script does a Delete Task, based on an ini file. You can configure if it's recursive or not, and how old are the files you want to remove. It creates deletion logs and error logs, and sends an e-mail if something goes wrong. This is script has been very useful for some application servers, since some application creates a big pile of logs and every now and then, it becomes big enough to generate performance issues. It configured as a Scheduled Task, the script will be very useful, deleting those logs older than what I configure at the ini file. Well, there it is: expandcollapse popup#Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_icon=S:\AUTOMATIZACAO\weg.ico #AutoIt3Wrapper_outfile=DeleteFiles.exe #AutoIt3Wrapper_Compression=0 #AutoIt3Wrapper_Res_Comment=Deleta Arquivos #AutoIt3Wrapper_Res_Description=Developed by DavidLago (HELLFROST) #AutoIt3Wrapper_Res_Fileversion=1.0.0.3 #AutoIt3Wrapper_Res_LegalCopyright=Hellfrost - David Lago #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #cs ---------------------------Script Start------------------------------------- AutoIt Version: 3.3.6.1 Author: David Lago AKA Hellfrost Script Function: Delete files based on an .ini file. #ce ---------------------------------------------------------------------------- $ExeError = ObjEvent("AutoIt.Error", "ComError") #include <GuiConstantsEx.au3> #include <WindowsConstants.au3> #include <array.au3> #include <INet.au3> #include <Date.au3> If Not FileExists(@ScriptDir & "\LOG") Then DirCreate(@ScriptDir & "\LOG") EndIf If Not FileExists(@ScriptDir & "\Config.ini") Then $NoIniFileMsg = "The Script " & @ScriptName & ", at " $NoIniFileMsg = $NoIniFileMsg & "Computer/Server " & @ComputerName & ", does not have a config.ini file at its same dir " & @CRLF & @CRLF $NoIniFileMsg = $NoIniFileMsg & "Script path at the Computer / Server: " & @ScriptFullPath SendMail($NoIniFileMsg, "Script Alert: " & @ScriptName) Exit EndIf Global $Hora = @HOUR & @MIN Global $Data = @YEAR & @MON & @MDAY Global $logFileDeletion = @ScriptDir & "\LOG\" & "DeleteJob - " & $Data & "_" & $Hora & ".log" Global $Caminho_logs = @ScriptDir & "\LOG\" $ValidadeArquivo = IniRead("Config.ini", "Geral", "ValidadeArquivo", "15") ScanFolder2($Caminho_logs, "*.*", $ValidadeArquivo, "N") $sources = IniReadSection("Config.ini", "Sources") ;-------SOURCES----------- Global $ManutencaoInic = IniRead("Config.ini", "Manutencao", "ManutencaoInic", "N") Global $ManutencaoFim = IniRead("Config.ini", "Manutencao", "ManutencaoFim", "N") Global $LogFile = $Data & "_" & IniRead("Config.ini", "Log", "LogFile", "") Global $LogErro = IniRead("Config.ini", "Log", "LogErro", "") & "_" ; & $Data & ".log" Global $LogValidade = IniRead("Config.ini", "Log", "LogValidade", "15") Global $logFileError = @ScriptDir & "\LOG\" & $LogErro & $Data & "_" & $Hora & ".log" Global $AlertaConf = IniRead("Config.ini", "Alerta", "AlertaConf", "N") Global $AlertaDadosFrom = IniRead("Config.ini", "Alerta", "AlertaDadosFrom", "") Global $AlertaDadosTo = IniRead("Config.ini", "Alerta", "AlertaDadosTo", "") Global $AlertaDadosSubj = IniRead("Config.ini", "Alerta", "AlertaDadosSubj", "") Global $MensagemManutencao = "The Script " & @ScriptFullPath & " at " & @ComputerName & ", is under maintenance since " & $ManutencaoInic & " and was not " _ & "run. It is set to end at " & $ManutencaoFim & ". In case you need any help, contact your Domain Admin." ;-------- Maintenance ----------------- If $ManutencaoInic <> "" Then If $ManutencaoInic <> "N" Then Sendmail($MensagemManutencao, "The DeleteJob Script was not run due to maintenance") Exit EndIf EndIf ;-------- Dir Validate & Error ----------------- If @error Then Else For $i = 1 To $sources[0][0] $source_folder = $sources[$i][0] $split_value = StringSplit($sources[$i][1], ";") $source_extension = StringUpper($split_value[1]) $source_days = Number($split_value[2]) $Recursivo = StringUpper($split_value[3]) If FileExists($source_folder) Then ScanFolder2($source_folder, $source_extension, $source_days, $Recursivo) Else $mensagem = "The folder " & $source_folder & " was not located (Check the ini file)." & @CRLF & @CRLF $mensagem = $mensagem & "This script was run at the computer/server " & @ComputerName & @CRLF & @CRLF $mensagem = $mensagem & "Script: " & @ScriptFullPath SendMail($mensagem, "Script Alert: " & @ScriptName) EndIf Next EndIf Exit ;----------------------------------------------- Func ScanFolder2($param_SourceFolder, $param_extensao, $param_days, $param_recursivo) Local $Search Local $File Local $FileAttributes Local $FullFilePath Local $ExtensaoCheck If $param_recursivo = "N" Then ; If the parameter is not set to recursive $Search = FileFindFirstFile($param_SourceFolder & "\" & $param_extensao) If $Search = -1 Then ;Not found! Else ;Found! While 1 $File = FileFindNextFile($Search) If @error Then ExitLoop $FullFilePath = $param_SourceFolder & "\" & $File $t = FileGetTime($FullFilePath, 0, 0) $yyyymdhms = $t[0] & "/" & $t[1] & "/" & $t[2] & " " & $t[3] & ":" & $t[4] & ":" & $t[5] $iDateCalc = _DateDiff("D", $yyyymdhms, _NowCalc()) If $iDateCalc > $param_days Then If FileDelete($FullFilePath) = 1 Then FileWriteLine($logFileDeletion, $FullFilePath & ";" & $t) Else FileWriteLine("\LOG\" & $LogErro, $FullFilePath & ";" & $t) EndIf EndIf WEnd EndIf Else $Search = FileFindFirstFile($param_SourceFolder & "\*.*") If $Search = -1 Then ;Not Found! Else ;Found! While 1 $File = FileFindNextFile($Search) If @error Then ExitLoop ;Are you a folder? $FullFilePath = $param_SourceFolder & "\" & $File $FileAttributes = FileGetAttrib($FullFilePath) If StringInStr($FileAttributes, "D") Then ;Yes, I'm a folder! ;Am I in "Sources"? $retorno_search = _ArraySearch($sources, $FullFilePath, 0, 0, 0, 0, 1, 0) If $retorno_search = -1 Then ScanFolder2($FullFilePath, $param_extensao, $param_days, $param_recursivo) EndIf Else $file_extension = StringUpper("*" & StringMid($File, StringInStr($File, ".", 0, -1))) If $file_extension = $param_extensao Or $param_extensao = "*.*" Then $t = FileGetTime($FullFilePath, 0, 0) $yyyymdhms = $t[0] & "/" & $t[1] & "/" & $t[2] & " " & $t[3] & ":" & $t[4] & ":" & $t[5] $iDateCalc = _DateDiff("D", $yyyymdhms, _NowCalc()) If $iDateCalc > $param_days Then If FileDelete($FullFilePath) = 1 Then FileWriteLine($logFileDeletion, $FullFilePath & ";" & $t) Else FileWriteLine($logFileError, $FullFilePath & ";" & $t) EndIf Else EndIf EndIf EndIf WEnd EndIf EndIf EndFunc ;==>ScanFolder2 ; Function to send e-mail Func SendMail($param_body, $param_subject) $objEmail = ObjCreate("CDO.Message") $objEmail.From = $AlertaDadosFrom $objEmail.To = $AlertaDadosTo $objEmail.Subject = $param_subject $objEmail.Textbody = $param_body $objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 $objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _ "SMTPServer.net" ; <--------------------------------------------------- CONFIGURE YOUR SMPT SERVER CORRECTLY! $objEmail.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 $objEmail.Configuration.Fields.Update $objEmail.Send EndFunc ;==>SendMail #cs ---------------------------Script End--------------------------------------- AutoIt Version: 3.3.6.1 Author: David Lago Script Function: Deleção de arquivos seguindo regras especÃficas, com base em um arquivo de configuração (ini). #ce ---------------------------------------------------------------------------- The config. ini file is this one below. Just copy the content and paste it on the notepad, and save at the scriptdir with the name "config.ini" expandcollapse popup#--------------------------------------------------------------------# # Config. ini # #--------------------------------------------------------------------# #--------------------------------------------------------------------# # SOURCES Pattern: C:\folder = *.extension ; DaysOld ; Recursive # #--------------------------------------------------------------------# [Sources] C:\Folder\Test\Delete=*.*;7;N [Log] ##### Logfile Names ##### LogFile = DeleteJob LogErro = Error ##### Logfile Retention ##### LogValidade = 15 [Alerta] ##### Alert via E-mail (From, To , Subject) ##### AlertaDadosFrom = DeleteJob@AutoItScripts.com AlertaDadosTo = YourEmail@Hotmail.com AlertaDadosSubj = Error while running a script [Manutencao] ##### Maintenance: The period that the script will not run (If there is none, leave the field blank). Patten: "DD/MM/YYYY at HH:MM" ##### ManutencaoInic = ManutencaoFim = If you get any suggestion or improvement, PLEASE let me know DeleteFiles.au3 Link to comment Share on other sites More sharing options...
DavidLago Posted July 6, 2011 Author Share Posted July 6, 2011 NOTE: I am Brazilian, then I speak portuguese. I couldn't avoid having the variables in portuguese. Sorry about that Link to comment Share on other sites More sharing options...
TomDuDolan Posted July 8, 2011 Share Posted July 8, 2011 NOTE:I am Brazilian, then I speak portuguese. I couldn't avoid having the variables in portuguese. Sorry about that You should use Google Translator, although it's not 100% accurate, it will give us a likely idea of the translation.Going to try this script out. Will report back.-T My ickle pieces of software :3Radio Scriptr //Almost completeSimple IP/URL pinger, my first program. //CompletedSimple Downloader // Working - basic stateOn-GoingRadio Scriptr - Radio Server. Link to comment Share on other sites More sharing options...
DavidLago Posted July 12, 2011 Author Share Posted July 12, 2011 Actually I speak english fluently. There is no need for the translator. The thing is, I created this script to use on our servers, so, my intention, at least when I started, wasn't posting here. Actually, if you have the idea, you can just switch all the variables at once using CTRL + H, - David Link to comment Share on other sites More sharing options...
Spiff59 Posted July 16, 2011 Share Posted July 16, 2011 The FileFindNextFile() function was modified a couple years ago to return a file/folder flag in the @extended field. It is much faster than using FileGetAttrib(). So... $File = FileFindNextFile($Search) If @error Then ExitLoop ;Are you a folder? $FullFilePath = $param_SourceFolder & "\" & $File $FileAttributes = FileGetAttrib($FullFilePath) If StringInStr($FileAttributes, "D") Then ;Yes, I'm a folder! could become... $File = FileFindNextFile($Search) If @error Then ExitLoop $FullFilePath = $param_SourceFolder & "\" & $File If @extended Then ;Yes, I'm a folder! Link to comment Share on other sites More sharing options...
DavidLago Posted July 22, 2011 Author Share Posted July 22, 2011 The FileFindNextFile() function was modified a couple years ago to return a file/folder flag in the @extended field. It is much faster than using FileGetAttrib(). So... $File = FileFindNextFile($Search) If @error Then ExitLoop ;Are you a folder? $FullFilePath = $param_SourceFolder & "\" & $File $FileAttributes = FileGetAttrib($FullFilePath) If StringInStr($FileAttributes, "D") Then ;Yes, I'm a folder! could become... $File = FileFindNextFile($Search) If @error Then ExitLoop $FullFilePath = $param_SourceFolder & "\" & $File If @extended Then ;Yes, I'm a folder! I didn't know that, Spiff59. Thanks a lot for the suggestion. I'll incorporate this in my Script. How do you get to know these things? Link to comment Share on other sites More sharing options...
DavidLago Posted July 22, 2011 Author Share Posted July 22, 2011 Oh, and By the way, I've been thinking about adding a new function to this script. Do you have any idea how could I configure to delete ONLY folders older than "X" days? and whatever is a file, will be left untouched? (Of course, files within the folders will be deleted, naturally). jtruono 1 Link to comment Share on other sites More sharing options...
jtruono Posted February 21, 2013 Share Posted February 21, 2013 Hey David, Great script. How do I get it to delete folders? Did you ever get it to just delete folders. I had fun converting to English, then I found this post & Ctrl H Thanks, & keepup GR8 work Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now