Power shell script to delete some old data to free up space upto certain limit

The problem is, that you need to make the WMI query again, every time after deleting a subfolder, so the free space is updated.

Check out my version:

$drive = "D:"
$directory = "$drive\Suba\Suba"
$desiredSpace = 262 * 1gb

$subfolders = [System.Collections.ArrayList]@(Get-ChildItem $directory | where { $_.PSIsContainer } | sort LastWriteTime)
while (([wmi]"Win32_LogicalDisk.DeviceID='$drive'").FreeSpace -lt $desiredSpace) {
    if ($subfolders.Count -eq 0) {
        Write-Warning "Not enough sub-folders to delete."
        break
    }
    Remove-Item $subfolders[0].FullName -Recurse -Force -Confirm:$false
    $subfolders.RemoveAt(0)
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top