Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 476
  • Last Modified:

Powershell script to delete files in a folder based on age

I need a powershell script to perform the following:
1.  Determine the size a particular drive
2.  If free-space is less than say 10% then delete oldest .csv files from specific directories

Background:
System Event log files are archived as csv files for specific event types...Application, security, etc.  The path is something like e:\Saved_logs\Application;  e:\Saved_logs\Security; etc.  Each of these subfolders contain csv files that contain a servername-timestamp.csv file
(ex: servername-01012015-midnight.csv).  There may be 20 files covering 20 servers for a particular time frame.  The idea is, if the the freespace of the volume is less than 10% then search in each of these subfolders and delete the oldest files by date.
0
BigmacMc
Asked:
BigmacMc
  • 2
1 Solution
 
noxchoCommented:
Get-ChildItem M:\ | Sort CreationTime | Select -Last 1 | Remove-Item

This way you can delete the oldest file if you have in this folder only the specific extension files.
Here Bryan made an excellent work: http://www.codeproject.com/Articles/564957/Clean-Up-Old-Files-using-PowerShell
Seems like exactly what you need.
0
 
QlemoC++ DeveloperCommented:
There are several ways to approach this, and it is kind of open as you didn't say exactly which files should get deleted.

For example, we could go into a loop and delete the oldest file found in all folders, until free space is ok again.
[WMI] $disksize = "Win32_LogicalDisk.DeviceID='E:'".Size
$percfree = $part.FreeSpace/$part.Size * 100.0
while (([WMI] "Win32_LogicalDisk.DeviceID='E:'").FreeSpace / $disksize * 100.0 -lt 10.0)
{
  get-childitem -recurse 'E:\Saved_logs\' | ? { !$_.PsIsContainer } | sort CreationTime |
    select -First 1 | Remove-Item
}

Open in new window

Or we could just delete the oldest file of each folder.
[WMI] $part = "Win32_LogicalDisk.DeviceID='E:'"
if ($part.FreeSpace/$part.Size*100.0 -lt 10.0)
{
   foreach ($root in 'E:\Saved_logs\Application', 'E:\Saved_logs\Security')
   {
      get-childitem $root -recurse | sort CreationTime | select -First 1 | Remove-Item
   }
}

Open in new window

Note that you have to use -First, not -Last as shown by noxcho, to get the oldest file.
0
 
BigmacMcAuthor Commented:
Thanks for the feedback.  I'll try this out over the weekend.
0
 
BigmacMcAuthor Commented:
Qlemo - the 2nd one worked brilliantly.  This work for me.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now