Solved

PowerShell question delete files by date

Posted on 2016-08-19
2
40 Views
Last Modified: 2016-08-25
I have a folder called MAX that has files in it and subdirectories in it.   I need a powershell script that deletes files older than 15 days that are located in folder max but does not touch any of the subdirectories or any of the files in the subdirectories in MAX.
0
Comment
Question by:jamesmetcalf74
2 Comments
 
LVL 84

Accepted Solution

by:
oBdA earned 250 total points
ID: 41763125
In test mode, remove the -WhatIf to run it for real.
PS 3.0 or later:
$CutOff = (Get-Date).AddDays(-15)
Get-ChildItem C:\Test\Max -File | ? {$_.LastWriteTime -lt $CutOff} | Remove-Item -WhatIf

Open in new window

PS 2.0:
$CutOff = (Get-Date).AddDays(-15)
Get-ChildItem C:\Test\Max | ? {!$_.PsIsContainer -and ($_.LastWriteTime -lt $CutOff)} | Remove-Item -WhatIf

Open in new window

0
 
LVL 9

Assisted Solution

by:Tim Edwards
Tim Edwards earned 250 total points
ID: 41763131
This is the code that I have a scheduled task to cleanup backup files older than x amount of days and it works well
#Delete Mitel Controller Backups older than 3 Days#

#defined Parameters#

$Date = Get-Date
$Days = "3"
$TargetDrive = "M:\"

#defined extension#

$Extension = "*.tar"

#define LastWriteTime based on number of days#
$LastWrite = $Date.AddDays(-$Days)

#get files based on lastwrite filter and specified folder#
$Files = Get-Childitem $TargetDrive -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}

foreach ($File in $Files)
    {
    if ($File -ne $NULL)
        {
        write-host "Deleting File $File" -ForegroundColor "DarkRed"
        Remove-Item $File.FullName | out-null
        }
    else
        {
        Write-Host "No more files to delete!" -foregroundcolor "Green"
        }
    }

Open in new window

0

Featured Post

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

"Migrate" an SMTP relay receive connector to a new server using info from an old server.
This script can help you clean up your user profile database by comparing profiles to Active Directory users in a particular OU, and removing the profiles that don't match.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question