Usuário com melhor resposta
Script Para deletar arquivos e subpastas

Pergunta
-
Boa noite amigos.
Tenho um servidor com um pasta onde todo mundo faz o que quer nela.
preciso de um script que delete todos os arquivos, pastas e subpastas dentro dela todas as noites. Eu já tentei varias formas porém só consigo apagar os arquivos e pastas que estão vazias, se as pastas contem informação ela não é excluída, alguém tem alguma solução.
Já utilizei o script abaixo
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSubfolders = objWMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='c:\Geral'} " _
& "WHERE AssocClass = Win32_Subdirectory " _
& "ResultRole = PartComponent")
For Each objFolder in colSubfolders
errResults = objFolder.Delete
Wscript.Echo errResults
Next
Respostas
-
Cara este script apaga arquivos e pastas com um determinado tempo de vida.
Só vc colocar a idade 0 ou 1 .
Nos comentários está tudo explicado!!!
Boa sorte abraço.
Code Snippet'-----------------------------------------------------------------------------------------
'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 " & "<Folder>" & " <no_days_old>"
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 IfSet 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 IfEnd Sub
'------------------------------------------------------------------------------------------
'End of DeleteOldFiles
'------------------------------------------------------------------------------------------
-
Olá,
segue minha dica:
1) Instale o Windows Powershell nesse servidor
2) Use a seguinte linha para apagar os arquivos, pastas e subpastas:
rm * -recurse -force
Existem outras soluções... desde as que usam WMI, somente o Windows Scripting Host e por aí vai... essa é somente uma das mais simples.
[]s,
Vinicius Canto
MVP Scripting -
Olá,
tudo que você precisa é salvar este arquivo com o nome de DelOldFiles.vbs. Depois, é só abrir um prompt de comando e digitar wscript DelOldFiles.vbs g:\pasta
O nome do arquivo pode até ser outro, mas o comando é esse.
[]s,
--
Vinicius Canto <scripterbr_at_gmail_dot_com>
MVP Visual Developer - Scripting
MCP Windows 2000 Server, Windows XP e SQL Server 2000
Bacharelando em Ciências da Computação - USP
Blog sobre scripting: http://viniciuscanto.blogspot.com -
isso por que faltou o parâmetro dos dias (tempo de vida dos arquivos e pastas) no seu caso coloque "0" ou "1"
Veja DelOldFiles.vbs "c:\temp" 7 -> tempo de vida dos arquivos e pastas
| |_____
Nome do arquivo |
caminho da pasta
Boa sorte, e abraço.
Todas as Respostas
-
Cara este script apaga arquivos e pastas com um determinado tempo de vida.
Só vc colocar a idade 0 ou 1 .
Nos comentários está tudo explicado!!!
Boa sorte abraço.
Code Snippet'-----------------------------------------------------------------------------------------
'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 " & "<Folder>" & " <no_days_old>"
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 IfSet 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 IfEnd Sub
'------------------------------------------------------------------------------------------
'End of DeleteOldFiles
'------------------------------------------------------------------------------------------
-
-
Olá,
segue minha dica:
1) Instale o Windows Powershell nesse servidor
2) Use a seguinte linha para apagar os arquivos, pastas e subpastas:
rm * -recurse -force
Existem outras soluções... desde as que usam WMI, somente o Windows Scripting Host e por aí vai... essa é somente uma das mais simples.
[]s,
Vinicius Canto
MVP Scripting -
-
-
Olá,
tudo que você precisa é salvar este arquivo com o nome de DelOldFiles.vbs. Depois, é só abrir um prompt de comando e digitar wscript DelOldFiles.vbs g:\pasta
O nome do arquivo pode até ser outro, mas o comando é esse.
[]s,
--
Vinicius Canto <scripterbr_at_gmail_dot_com>
MVP Visual Developer - Scripting
MCP Windows 2000 Server, Windows XP e SQL Server 2000
Bacharelando em Ciências da Computação - USP
Blog sobre scripting: http://viniciuscanto.blogspot.com -
-
isso por que faltou o parâmetro dos dias (tempo de vida dos arquivos e pastas) no seu caso coloque "0" ou "1"
Veja DelOldFiles.vbs "c:\temp" 7 -> tempo de vida dos arquivos e pastas
| |_____
Nome do arquivo |
caminho da pasta
Boa sorte, e abraço.
-