Search code examples
powershellscheduled-tasks

Delete certain type of files when disk usage is below a treshold


I have a powershell script that runs everyday as a scheduledjob and deletes any logs over 30 days old. However, I want for the script to also delete these same files if there is less than 5 GB free disk space. Any ideas what would be the best approach to that?

Here's how the script currently looks:

Unregister-ScheduledJob -Name LogRotation -ErrorAction SilentlyContinue
wevtutil set-log Microsoft-Windows-TaskScheduler/Operational /enabled:true
$T = New-JobTrigger -Daily -At "12:37 PM" -DaysInterval 1  
$O = @{
WakeToRun=$true
StartIfNotIdle=$false
MultipleInstancePolicy="Queue"
}
$SB = Get-ChildItem "C:\Folder\*" -Recurse -Include *.log | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30))} | Remove-Item
Register-ScheduledJob -Trigger $T -ScheduledJobOption $O -Name CTLogRotation -ScriptBlock {$SB}

Solution

  • You could first check the remaining disk space. Then create a different scriptblock when that free space is less than 5Gb

    if (((Get-Volume -DriveLetter C).SizeRemaining / 1Gb) -lt 5) {
        # delete all log files if the remaining size in GB is less than 5
        $SB = Get-ChildItem "C:\Folder" -Recurse -Filter '*.log' -File | Remove-Item -Force
    }
    else {
        # delete all log files older than 30 days
        $SB = Get-ChildItem "C:\Folder" -Recurse -Filter '*.log' -File | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-30).Date)} | Remove-Item -Force
    }
    

    P.S. I'm using -Filter '*.log', because that is way faster than -Include.
    -Filter can however have just one file pattern.
    I also added switch -File, so the code does not look for directories