script to delete files...

hi all,

In my organisation, we are deleting files older than 36hrs every time. we are doing it manually. can anyone please help me to build a script which runs in windows server 2012. which i can use in scheduler to run automatically.
ramachandrawithuAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Professor JMicrosoft Excel ExpertCommented:
you can try with this

Change the sRoot and nMaxFileAge variables to suit your needs.To run the script periodically, save it to a location like C:\Scripts\delete_old_files.vbs and create a scheduled task with a Run setting of "cscript //B C:\Scripts\delete_old_files.vbs"

On Error Resume Next

Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = "C:\YourPath To Old Files"			'Path root to look for files
today = Date
nMaxFileAge = 36					'Files older than this (in days) will be deleted

DeleteFiles(sRoot)

Function DeleteFiles(ByVal sFolder)

	Set oFolder = oFileSys.GetFolder(sFolder)
	Set aFiles = oFolder.Files
	Set aSubFolders = oFolder.SubFolders

	For Each file in aFiles
		dFileCreated = FormatDateTime(file.DateCreated, "2")
		If DateDiff("d", dFileCreated, today) > nMaxFileAge Then
			file.Delete(True)
		End If
	Next

	For Each folder in aSubFolders
		DeleteFiles(folder.Path)
	Next

End Function

Open in new window



or if you want a more advanced version, then please refer here
Bill PrewIT / Software Engineering ConsultantCommented:
Do you need to process subfolders, or just the files in one folder?

If just one folder my simple approach in VBS would be as follows.

Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder("c:\temp")
For Each objFile In objFolder.Files
   If DateDiff("h", objFile.DateLastModified, Now) > 36 Then 
      objFile.Delete(True)
   End If
Next

Open in new window

~bp
David Johnson, CD, MVPRetiredCommented:
powershell
function delete-oldfiles {
<#
.Synopsis
   Deletes files starting at a base location with a last modified date older than a Maximum Age
.DESCRIPTION
   Long description
.EXAMPLE
   delete-oldfiles.ps1 -basefolder c:\temp\ -maxage 30
.EXAMPLE
   delete-oldfiles.ps1 will delete files from c:\temp and subfolders with a modified date of more than 3 days ago
.EXAMPLE
delete-oldfiles -BasePath c:\abcd  will delete files from c:\abcd and subfolders with a modified date of more than 3 days ago
.EXAMPLE
delete-oldfiles -Maxage 180 will delete files from c:\temp and subfolders with a modified date of more than 180 days ago
.INPUTS
   Inputs to this cmdlet (if any)
.OUTPUTS
   none
    #>
    [CmdletBinding()]
    Param ( [string] $BaseFolder = 'c:\temp',[int] $MaximumAge = '3' )
    write-Debug ($BaseFolder)
    write-Debug ($MaximumAge)
    $cutoffdate= (get-date).adddays(-1 * $maximumage)
    $files = Get-ChildItem -Path $BaseFolder -Recurse 
    foreach($file in $files){
    if  ($file.LastWriteTime -lt $cutoffdate) 
                { 
#remove -whatif if done testing
                remove-item -Path $file.FullName -whatif
                }
    }
}

Open in new window

OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

aikimarkCommented:
@ProfessorJimJam

Did you mean to use 36 days difference as your criterion?
I expected to see this:
If DateDiff("h", dFileCreated, today) > nMaxFileAge Then

Open in new window

Professor JMicrosoft Excel ExpertCommented:
Aikimark
Many thanks for spotting that issue, it was incorrect to have d because it was 36 hours not 36 days.

So, my first post code line # 18 "d" to be replaced by "h".

Thanks again
Professor JMicrosoft Excel ExpertCommented:
corrected code

thanks to aikimark

On Error Resume Next

Set oFileSys = WScript.CreateObject("Scripting.FileSystemObject")
sRoot = "C:\YourPath To Old Files"			'Path root to look for files
today = Date
nMaxFileAge = 36					'Files older than this (in days) will be deleted

DeleteFiles(sRoot)

Function DeleteFiles(ByVal sFolder)

	Set oFolder = oFileSys.GetFolder(sFolder)
	Set aFiles = oFolder.Files
	Set aSubFolders = oFolder.SubFolders

	For Each file in aFiles
		dFileCreated = FormatDateTime(file.DateCreated, "2")
		If DateDiff("h", dFileCreated, today) > nMaxFileAge Then
			file.Delete(True)
		End If
	Next

	For Each folder in aSubFolders
		DeleteFiles(folder.Path)
	Next

End Function

Open in new window

David Johnson, CD, MVPRetiredCommented:
changed days to hours
function delete-oldfiles {
<#
.Synopsis
   Deletes files starting at a base location with a last modified date older than a Maximum Hours
.DESCRIPTION
   Long description
.EXAMPLE
   delete-oldfiles.ps1 -basefolder c:\temp\ -maxHours 30
.EXAMPLE
   delete-oldfiles.ps1 will delete files from c:\temp and subfolders with a modified date of more than 3 days ago
.EXAMPLE
delete-oldfiles -BasePath c:\abcd  will delete files from c:\abcd and subfolders with a modified date of more than 36 hours ago
.EXAMPLE
delete-oldfiles -MaxHours 180 will delete files from c:\temp and subfolders with a modified date of more than 180 hours ago
.INPUTS
   Inputs to this cmdlet (if any)
.OUTPUTS
   none
    #>
    [CmdletBinding()]
    Param ( [string] $BaseFolder = 'c:\temp',[int] $MaximumHours = '36' )
    write-Debug ($BaseFolder)
    write-Debug ($MaximumHours)
    $cutoffdate= (get-date).addhours(-1 * $maximumHours)
    $files = Get-ChildItem -Path $BaseFolder -Recurse 
    foreach($file in $files){
    if  ($file.LastWriteTime -lt $cutoffdate) 
                { 
#remove -whatif if done testing
                remove-item -Path $file.FullName -whatif
                }
    }
}

Open in new window

aikimarkCommented:
@ramachandrawithu

How many files are in the directory (tree?) and what percentage of the files are usually eligible for deletion?
ramachandrawithuAuthor Commented:
sorry for the late response.

my requirement is, we have a server and we created one folder and gave access to all the users. in that, we need to delete files and folders which are not used more than 2 days (48 hrs - preferably in hours calculation only.). but the script should check that before deleting the folder it should check all the sub-folders and files with in that sub folders.

almost 20 to 25% of files eligible for deletion and that main folder is almost more than 80 GB data is there.
Bill PrewIT / Software Engineering ConsultantCommented:
Okay, based on that I would approach it with the script below.  Save it as a VBS and schedule it via Task Scheduler.  Of course, test thoroughly before running against the production folders.  A few notes:

Adjust the two lines at the top for your folder, and age to keep in hours
It does error checking so that if it hits a folder it can not access it skips it rather than error out
It removes all files older that the hours specified based on last modification date of the file
It recurses into all subfolders of the base folder
If a folder currently exists with no files or subfolders in it, it is not removed
If a folder currently exists with files or subfolders in it, but after purging old files and folders within it becomes empty, then it is deleted
You didn't ask for any logging or stats at the end, so none are included, but that would be easy to add

' Specify base folder to purge, and age in hours of files to keep
Const strBaseDir = "C:\Temp"
Const intAgeInHours = 36

' Create file system object
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")

' Remove old files recursively
RemoveOldFiles objFSO.GetFolder(strBaseDir)

Sub RemoveOldFiles(objFolder)
    On Error Resume Next

    ' If no files of subfolders exist on first check, leave it alone
    If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
        Exit Sub
    End If

    ' Remove any files older than specified days from this folder
    For Each objFile In objFolder.Files
        If DateDiff("h", objFile.DateLastModified, Now) > intAgeInHours Then
            objFile.Delete
        End If
    Next

    ' See if we were able to access this folder, if not don't recurse into it
    If Err.Number = 0 Then
        ' Remove all older files in any subfolders of this one
        For Each objSubFolder In objFolder.Subfolders
            RemoveOldFiles objSubFolder
        Next
    End If

    ' If folder is now empty, we purged its contents, so remove it
    If objFolder.Files.Count = 0 And objFolder.Subfolders.Count = 0 Then
        objFolder.Delete
    End If
End Sub

Open in new window

~bp

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
VB Script

From novice to tech pro — start learning today.