none
Apagar arquivos com mais de 48 horas mantendo uma estrutura de diretórios RRS feed

  • Pergunta

  •  

    Sou novo por aqui e gostei do que já vi até agora pesquisando no fórum, porém gostaria de saber se alguém teria algum script ou que me ajudasse a criar um para realizar a seguinte tarefa, pois na verdade até encontrei alguns scripts parecidos, mais não consegui organiza-los para chegar ao objetivo.

     

    Tenho uma área compartilhada chamada de "TransferenciaDados" para que usuários de departamentos diferentes possam efetuar troca de arquivos, neste existem alguns subdiretórios, que possuem permissões específicas para que apenas os usuários que necessitam trocar arquivos tenham acesso.

     

    A tarefa que necessito executar e a seguinte:

     

    - apagar os arquivos com mais de 48 horas a partir da data de criação

    - gerar um arquivo de log com os arquivos e diretórios apagados

    - apagar somente a estrutura de diretórios a partir do segundo nível, por exemplo:

     

    - TransferenciaDados (Diretório Principal) - 01º Nível

     - TI (2º Nível)

    - Apagar a partir deste nível (arquivos e se o diretório estiver vazio também apagar)

     

     

    Valeu, obrigado.

    sexta-feira, 11 de janeiro de 2008 13:00

Respostas

  • testa esse

    ftp://ftp.sac.sk/pub/sac/utilfile/purger.zip

     

    e também esse:

    Talves vc tenha que fazer algumas modificações no script ou trabalhar com acl de pastas diferentes de arquivos.

    boa sorte.

    Ps1.: Não retire o mérito da pessoa que criou o script apagando os comentários.

    Ps2: tenho certeza que os dois funcionam.

     

    Abnraço.

     

    '-----------------------------------------------------------------------------------------
    'DelOldFiles.vbs - 4/22/2000
    '
    'Purpose: Deletes files and folders older than a given number of days (based on Last
    '   Modified Date) from a specified folder and ALL of its subdirectories.
    '
    'Prerequisites: Get WSH 2.0 at
    '  http://msdn.microsoft.com/scripting/default.htm?/scripting/windowshost/
    '  You should also run this with CSCRIPT.EXE, not wscript.exe.
    '
    'Syntax: DelOldFiles.vbs <Folder> <no_days_old>
    '
    'Example: DelOldFiles.vbs "c:\temp" 7
    '         This will delete all files in c:\temp and its subdirectories that are 7 days old
    '
    'Notes: You will have to change the logfile path and name so that you can keep track of
    ' what was deleted. You can also comment out the delete statements (there are two
    '       of them) indicated by comments below to generate the logfile without actually
    '       deleting anything so you can make sure nothing important is being deleted.
    '
    'IMPORTANT: This script deletes files PERMANENTLY so make sure you know what you're doing.
    '
    'Copyright: Steve Seguis
    '           scriptmaster@scripthorizon.com
    '           www.scripthorizon.com
    '-----------------------------------------------------------------------------------------
    '=== Force declaration of ALL variables (variants)
    Option Explicit

    '=== Variables declaration required because of Option Explicit
    Dim fso
    Dim oArgs 
    Dim MyRootFolder
    Dim fsOut
    Dim logfile
    Dim outputString

    '=== CHANGE this to the path and name of the log file this script will output to.
    logfile = "DeletedFiles.log"

    '=== Constant Required for OpenTextFile function
    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    '=== Get the command line arguments
    Set oArgs = Wscript.Arguments
    If oArgs.Count < 2 Then
     Wscript.Echo "USAGE: DelOldFiles " & "&lt;Folder&gt;" & " &lt;no_days_old&gt;"
     Wscript.Echo ""
     WScript.Echo "Example: DelOldFiles.vbs c:\temp 7"
     WScript.Echo "This will delete all files in c:\temp and its subdirectories"
     WScript.Echo "that are over 7 days old."
     Wscript.Quit 1
    End If

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set MyRootFolder = fso.GetFolder(oArgs(0))

    on error resume next 'fabio 21/05/2007

    '===First make sure if the folder exists
    IF NOT fso.FolderExists(MyRootFolder) Then
     fsOut.WriteLine oArgs(0) & "is not a valid Folder"
     WScript.Quit 1
    End If

    '=== Next make sure the third parameter is really a number
    If IsNumeric(oArgs(1)) Then
     If CInt(oArgs(1)) >= 0 Then
      '=== Get logfile object ready for appending
      Set fsOut = fso.OpenTextFile(logfile, ForAppending, True)
      fsOut.WriteLine now
      fsOut.WriteLine "Arquivo Ultima Modificação"
      '=== Call DeleteOldFiles on the current folder
      DeleteOldFiles MyRootFolder, oArgs(1)
     Else
      fsOut.WriteLine "The Second Parameter must a positive number"
      WScript.Quit 1
     End If
    Else
     fsOut.WriteLine "The Second Parameter must a positive number"
     WScript.Quit 1
    End If

    '=== Close logfile and quit
    fsOut.Close
    'WScript.Echo "Script Complete!"
    WScript.Quit 0


    '------------------------------------------------------------------------------------------
    'DeleteOldFiles(Folder,noDays)
    '
    'Purpose: Deletes files and subfolders in Folder that are noDays old.
    '------------------------------------------------------------------------------------------
    Sub DeleteOldFiles(Folder,noDays)
       '=== Varibles with local scope as we will this sub procedure recursively
       Dim Datedifference
       Dim MySubFolders
       Dim MyFiles
       Dim MyFile
       Dim MyFolder

       '=== Get the collection of Folders in this folder
       Set MySubFolders = Folder.SubFolders 

       '=== Get the collection of Files in this folder
       Set MyFiles = Folder.files

       '=== If there are subfolders, let process them first.
       IF MySubFolders.Count <> 0 Then
     For each MyFolder in MySubFolders
      DeleteOldFiles MyFolder, noDays
      'Se a pasta estiver vazia delete
      if Myfolder.files.count + Myfolder.SubFolders.count = 0 then
       MyFolder.Delete
      end if
     Next
       End If

       '=== If this folder isn't emtpy, process each file to see if they are older than
       '    the maximum age limit (noDays).
       IF MyFiles.Count <> 0 Then
     For Each MyFile in MyFiles
      '=== Find out how old the file is compared to current date
      Datedifference = DateDiff("D",MyFile.DateLastModified,Date)
      IF (Datedifference >= CInt(noDays)) Then
       '=== This file is old, delete and add entry to logfile
       outputString = MyFile.path & vbtab & MyFile.DateLastModified
       'WScript.Echo outputString
       fsOut.WriteLine outputString
       '=== If you just want to do a dry run of this script, comment out
       '    the next line to prevent the file from being deleted. The true
       '    after the delete statement is necessary to force delete
       MyFile.delete true
      Else
       'Wscript.Echo MyFile.path & " is OK!"
      End If
            Next
       End If

       '=== If this folder is emtpy, meaning no subfolders or files, check if this folder
       '    is older than maximum age limit and delete accordingly
       If MySubFolders.Count = 0 And MyFiles.Count = 0 Then
     Datedifference = DateDiff("D",Folder.DateLastModified,Date)
     IF (Datedifference > CInt(noDays)) Then
      '=== This Folder is old, delete and add entry to logfile
      outputString = Folder.path & vbtab & Folder.DateLastModified
      'WScript.Echo outputString
      fsOut.WriteLine outputString
      '=== If you just want to do a dry run of this script, comment out
      '    the next line to prevent the file from being deleted. The true
      '    after the delete statement is necessary to force delete
      Folder.delete true
      Exit Sub
     Else
      'Wscript.Echo Folder.path & " is OK!"
     End If
       End If

    End Sub
    '------------------------------------------------------------------------------------------
    'End of DeleteOldFiles
    '------------------------------------------------------------------------------------------

     

    sexta-feira, 11 de janeiro de 2008 14:02

Todas as Respostas

  • testa esse

    ftp://ftp.sac.sk/pub/sac/utilfile/purger.zip

     

    e também esse:

    Talves vc tenha que fazer algumas modificações no script ou trabalhar com acl de pastas diferentes de arquivos.

    boa sorte.

    Ps1.: Não retire o mérito da pessoa que criou o script apagando os comentários.

    Ps2: tenho certeza que os dois funcionam.

     

    Abnraço.

     

    '-----------------------------------------------------------------------------------------
    'DelOldFiles.vbs - 4/22/2000
    '
    'Purpose: Deletes files and folders older than a given number of days (based on Last
    '   Modified Date) from a specified folder and ALL of its subdirectories.
    '
    'Prerequisites: Get WSH 2.0 at
    '  http://msdn.microsoft.com/scripting/default.htm?/scripting/windowshost/
    '  You should also run this with CSCRIPT.EXE, not wscript.exe.
    '
    'Syntax: DelOldFiles.vbs &lt;Folder&gt; &lt;no_days_old&gt;
    '
    'Example: DelOldFiles.vbs "c:\temp" 7
    '         This will delete all files in c:\temp and its subdirectories that are 7 days old
    '
    'Notes: You will have to change the logfile path and name so that you can keep track of
    ' what was deleted. You can also comment out the delete statements (there are two
    '       of them) indicated by comments below to generate the logfile without actually
    '       deleting anything so you can make sure nothing important is being deleted.
    '
    'IMPORTANT: This script deletes files PERMANENTLY so make sure you know what you're doing.
    '
    'Copyright: Steve Seguis
    '           scriptmaster@scripthorizon.com
    '           www.scripthorizon.com
    '-----------------------------------------------------------------------------------------
    '=== Force declaration of ALL variables (variants)
    Option Explicit

    '=== Variables declaration required because of Option Explicit
    Dim fso
    Dim oArgs 
    Dim MyRootFolder
    Dim fsOut
    Dim logfile
    Dim outputString

    '=== CHANGE this to the path and name of the log file this script will output to.
    logfile = "DeletedFiles.log"

    '=== Constant Required for OpenTextFile function
    Const ForReading = 1
    Const ForWriting = 2
    Const ForAppending = 8

    '=== Get the command line arguments
    Set oArgs = Wscript.Arguments
    If oArgs.Count < 2 Then
     Wscript.Echo "USAGE: DelOldFiles " & "&lt;Folder&gt;" & " &lt;no_days_old&gt;"
     Wscript.Echo ""
     WScript.Echo "Example: DelOldFiles.vbs c:\temp 7"
     WScript.Echo "This will delete all files in c:\temp and its subdirectories"
     WScript.Echo "that are over 7 days old."
     Wscript.Quit 1
    End If

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set MyRootFolder = fso.GetFolder(oArgs(0))

    on error resume next 'fabio 21/05/2007

    '===First make sure if the folder exists
    IF NOT fso.FolderExists(MyRootFolder) Then
     fsOut.WriteLine oArgs(0) & "is not a valid Folder"
     WScript.Quit 1
    End If

    '=== Next make sure the third parameter is really a number
    If IsNumeric(oArgs(1)) Then
     If CInt(oArgs(1)) >= 0 Then
      '=== Get logfile object ready for appending
      Set fsOut = fso.OpenTextFile(logfile, ForAppending, True)
      fsOut.WriteLine now
      fsOut.WriteLine "Arquivo Ultima Modificação"
      '=== Call DeleteOldFiles on the current folder
      DeleteOldFiles MyRootFolder, oArgs(1)
     Else
      fsOut.WriteLine "The Second Parameter must a positive number"
      WScript.Quit 1
     End If
    Else
     fsOut.WriteLine "The Second Parameter must a positive number"
     WScript.Quit 1
    End If

    '=== Close logfile and quit
    fsOut.Close
    'WScript.Echo "Script Complete!"
    WScript.Quit 0


    '------------------------------------------------------------------------------------------
    'DeleteOldFiles(Folder,noDays)
    '
    'Purpose: Deletes files and subfolders in Folder that are noDays old.
    '------------------------------------------------------------------------------------------
    Sub DeleteOldFiles(Folder,noDays)
       '=== Varibles with local scope as we will this sub procedure recursively
       Dim Datedifference
       Dim MySubFolders
       Dim MyFiles
       Dim MyFile
       Dim MyFolder

       '=== Get the collection of Folders in this folder
       Set MySubFolders = Folder.SubFolders 

       '=== Get the collection of Files in this folder
       Set MyFiles = Folder.files

       '=== If there are subfolders, let process them first.
       IF MySubFolders.Count <> 0 Then
     For each MyFolder in MySubFolders
      DeleteOldFiles MyFolder, noDays
      'Se a pasta estiver vazia delete
      if Myfolder.files.count + Myfolder.SubFolders.count = 0 then
       MyFolder.Delete
      end if
     Next
       End If

       '=== If this folder isn't emtpy, process each file to see if they are older than
       '    the maximum age limit (noDays).
       IF MyFiles.Count <> 0 Then
     For Each MyFile in MyFiles
      '=== Find out how old the file is compared to current date
      Datedifference = DateDiff("D",MyFile.DateLastModified,Date)
      IF (Datedifference >= CInt(noDays)) Then
       '=== This file is old, delete and add entry to logfile
       outputString = MyFile.path & vbtab & MyFile.DateLastModified
       'WScript.Echo outputString
       fsOut.WriteLine outputString
       '=== If you just want to do a dry run of this script, comment out
       '    the next line to prevent the file from being deleted. The true
       '    after the delete statement is necessary to force delete
       MyFile.delete true
      Else
       'Wscript.Echo MyFile.path & " is OK!"
      End If
            Next
       End If

       '=== If this folder is emtpy, meaning no subfolders or files, check if this folder
       '    is older than maximum age limit and delete accordingly
       If MySubFolders.Count = 0 And MyFiles.Count = 0 Then
     Datedifference = DateDiff("D",Folder.DateLastModified,Date)
     IF (Datedifference > CInt(noDays)) Then
      '=== This Folder is old, delete and add entry to logfile
      outputString = Folder.path & vbtab & Folder.DateLastModified
      'WScript.Echo outputString
      fsOut.WriteLine outputString
      '=== If you just want to do a dry run of this script, comment out
      '    the next line to prevent the file from being deleted. The true
      '    after the delete statement is necessary to force delete
      Folder.delete true
      Exit Sub
     Else
      'Wscript.Echo Folder.path & " is OK!"
     End If
       End If

    End Sub
    '------------------------------------------------------------------------------------------
    'End of DeleteOldFiles
    '------------------------------------------------------------------------------------------

     

    sexta-feira, 11 de janeiro de 2008 14:02
  • Veja também o seguinte link:

    http://forums.microsoft.com/Technet-BR/ShowPost.aspx?PostID=2654013&SiteID=29


    []s,

    Vinicius Canto - MVP
    Blog sobre Scripting: http://viniciuscanto.blogspot.com
    segunda-feira, 14 de janeiro de 2008 16:50
    Moderador
  • Vinícius,

     

    Deixa ver se eu entendi, o parâmetro "-rec" server para a pesquisa recursiva? Porém como faço para apagar somente a partir do 3º nível de diretórios?

     

    ls c:\dados -rec | where {$_.lastwritetime -lt (date).addDays(-10) -and $_.length -lt 50KB}

     

    Grato.

    segunda-feira, 14 de janeiro de 2008 22:38
  • Romeu,

     

    Obrigado pelas alternativas vou fazer alguns testes aqui e depois coloco o resultado.

     

    Grato.

    segunda-feira, 14 de janeiro de 2008 22:40
  • Basta alterar o c:\dados... ou ainda gerar primeiro uma lista dos diretórios a serem varridos e depois usar a linha para apagar os arquivos.

    Não sei se entendi muito bem tua dúvida, mas acho que é isso.

    []s,


    Vinicius Canto
    MVP Windows Server - Admin Frameworks
    Blog sobre scripting: http://viniciuscanto.blogspot.com
    terça-feira, 15 de janeiro de 2008 12:39
    Moderador