views:

103

answers:

2

Given a folder \localhost\c$\work\

I'd like to run a powershell script every 15 minutes that ensures 5gb of free space is available.

If < 5gb is available, remove the least recently used folder within work until >5gb is available.

Gravy for nice output that can be redirected to a log file.

Thoughts?

A: 

Well, that all depends on how your folders are "used". If there are no easy indicators you can try using the .NET FileSystemWatcher class to look for changes and remember them as well as a timestamp in a queue, ordered by access time. Then you can pick the next folder to delete from that queue. But it's certainly not pretty.

Joey
+2  A: 

To schedule the task, you can use the task scheduler (example here)

For a script you could use

param($WorkDirectory = 'c:\work'
    , $LogFile = 'c:\work\deletelog.txt' )

#Check to see if there is enough free space
if ( ( (Get-WmiObject -Query "SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = 'C:'").FreeSpace / 1GB ) -lt 5)
{
    #Get a list of the folders in the work directory
    $FoldersInWorkDirectory = @(Get-ChildItem $WorkDirectory | Where-Object {$_ -is [System.IO.DirectoryInfo]} | Sort-Object -Property LastWriteTime -Descending)
    $FolderCount = 0

    while ( ( (Get-WmiObject -Query "SELECT FreeSpace FROM Win32_LogicalDisk WHERE DeviceID = 'C:'").FreeSpace / 1GB ) -lt 5)
    {
            #Remove the directory and attendant files and log the deletion
     Remove-Item -Path $FoldersInWorkDirectory[$FolderCount].FullName -Recurse
      "$(Get-Date) Deleted $($FoldersInWorkDirectory[$FolderCount].FullName)" | Out-File -Append $LogFile

            $FolderCount++
    } 
}
Steven Murawski