Search code examples
powershellpowershell-2.0powershell-3.0

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


I am new to power shell script. I have a Power shell script to Check the available disk space and delete some old subfolders from a folder until the free space reaches threshold level.

My code deletes all the folders and it does not exit anywhere. I am checking if free space is greater than available space and trying to terminating it. ( $part.FreeSpace -gt $desiredBytes)..

I have echoed $desiredBytes, $part.FreeSpace, $directoryInfo.count. Even if a folder of huge size gets deleted, the values of these variables are not getting updated. So, All the folders are getting deleted and still it does not terminate.

Could someone help me with this. Thanks in Advance :)

[WMI]$part = "Win32_LogicalDisk.DeviceID='D:'"
$directory = "D:\Suba\Suba\"
$desiredGiB = 262

$desiredBytes = $desiredGiB * 1073741824

$directoryInfo = Get-ChildItem $directory | Measure-Object
$directoryInfo.count #Returns the count of all of the objects in the directory

do{
if($part.FreeSpace -gt $desiredBytes)
{ exit
}
if ($directoryInfo.count -gt 0) {
echo $desiredBytes
echo $part.FreeSpace
echo $directoryInfo.count
    foreach ($root in $directory) {
      Get-ChildItem $root -Recurse |
            Sort-Object CreationTime |
             Select-Object -First 1 |
            Remove-Item -Force 
   }
 }
else
{ 
    Write-Host "Enough Files are not there in this directory!!"
    exit
}
}
while($part.FreeSpace -lt $desiredBytes)

Solution

  • 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)
    }