script to delete files...

ramachandrawithu
ramachandrawithu used Ask the Experts™
on
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.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Professor JMicrosoft Excel Expert
Top Expert 2014

Commented:
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 Consultant
Top Expert 2016

Commented:
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
Top Expert 2016

Commented:
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

Become a CompTIA Certified Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

Top Expert 2014

Commented:
@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 Expert
Top Expert 2014

Commented:
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 Expert
Top Expert 2014
Commented:
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

Top Expert 2016
Commented:
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

Top Expert 2014

Commented:
@ramachandrawithu

How many files are in the directory (tree?) and what percentage of the files are usually eligible for deletion?

Author

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.
IT / Software Engineering Consultant
Top Expert 2016
Commented:
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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial