Question

Given a folder, say \\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.

Thoughts?

Was it helpful?

Solution

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++
    } 
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top