You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBScript实现备份目录超阈值时删除最旧文件夹的技术问询

Handling Backup Directory Cleanup When Disk Space Exceeds 50GB

Hey there! I see you're new to batch/VBS scripting and need to automate cleaning up old backup folders when your main backups directory grows beyond 50GB. Let's break this down and adjust that VBScript you found to work with folders instead of files, plus I'll throw in a batch script option in case you prefer sticking with BAT.

Modified VBScript for Folder Cleanup

The original script you shared works for deleting individual files, but we can tweak it to target subfolders instead. Here's the adjusted version tailored to your backup directory setup:

Set fso = CreateObject("Scripting.FileSystemObject")
' Replace this path with your actual backups main directory
Set mainFolder = fso.GetFolder("C:\path\to\backups")

' 50GB in bytes (1GB = 2^30 bytes, so 50*2^30)
Const MAX_SIZE = 50 * 2^30

' Check if main folder exceeds the size limit
If mainFolder.Size > MAX_SIZE Then
    ' Use a recordset to sort subfolders by last modified date
    Set rs = CreateObject("ADODB.Recordset")
    With rs
        .Fields.Append "LastModified", 7 ' Date type for sorting
        .Fields.Append "FolderPath", 201, 5000 ' Text type to store folder path
        .Open
        
        ' Loop through all subfolders in the main backups directory
        For Each subFolder in mainFolder.SubFolders
            .AddNew
            .Fields("LastModified").Value = subFolder.DateLastModified
            .Fields("FolderPath").Value = subFolder.Path
            .Update
        Next
        
        ' Sort folders from OLDEST to NEWEST so we delete the oldest first
        .Sort = "LastModified ASC"
        
        Do While Not .EOF And mainFolder.Size > MAX_SIZE
            Dim folderToDelete
            folderToDelete = .Fields("FolderPath").Value
            
            ' Delete the folder and all its contents (force delete read-only items)
            fso.DeleteFolder folderToDelete, True
            
            ' Refresh the main folder size after deletion
            Set mainFolder = fso.GetFolder("C:\path\to\backups")
            
            .MoveNext
        Loop
    End With
End If

' Clean up unused objects
Set fso = Nothing
Set mainFolder = Nothing
Set rs = Nothing

Key Changes from the Original Script:

  • Switched from iterating over files to mainFolder.SubFolders
  • Replaced fso.DeleteFile with fso.DeleteFolder (the True flag ensures read-only content gets deleted too)
  • Adjusted the size limit to 50GB (50 * 2^30 bytes)
  • Sorted folders by oldest first so we prioritize deleting the earliest backups

Alternative Batch Script Option

If you'd prefer a batch script (since you mentioned being a BAT newbie), here's a straightforward version using built-in Windows commands:

@echo off
setlocal enabledelayedexpansion

' Set your main backups directory path
set "BACKUP_DIR=C:\path\to\backups"
' Set max allowed size in GB
set "MAX_SIZE_GB=50"
' Convert GB to bytes (1GB = 1073741824 bytes)
set /a MAX_SIZE_BYTES=MAX_SIZE_GB*1073741824

:CHECK_SIZE
' Calculate total size of the backup directory (without commas)
for /f "tokens=3" %%a in ('dir /s /-c "%BACKUP_DIR%" ^| findstr /i "bytes"') do set "TOTAL_SIZE=%%a"

' Check if we need to clean up
if !TOTAL_SIZE! gtr !MAX_SIZE_BYTES! (
    ' Find and delete the oldest subfolder
    echo Backup directory exceeds 50GB. Deleting oldest backup...
    for /f "delims=" %%f in ('forfiles /p "%BACKUP_DIR%" /s /m * /d -0 /c "cmd /c echo @fdate @ftime @path" ^| sort ^| findstr /v "%BACKUP_DIR%\." ^| findstr /v ".." ^| findstr /v "." ^| head -1') do (
        set "OLD_FOLDER=%%f"
        set "OLD_FOLDER=!OLD_FOLDER:* =!"
        set "OLD_FOLDER=!OLD_FOLDER:* =!"
        
        ' Delete the folder and all contents quietly
        rmdir /s /q "!OLD_FOLDER!"
        
        ' Re-check size after deletion
        goto CHECK_SIZE
    )
) else (
    echo Backup directory size is within limit. No cleanup needed.
)

endlocal

Quick Tips for Success

  1. Test first: Run the script on a copy of your backup directory before using it on the real thing to avoid accidental data loss
  2. Automate: Use Windows Task Scheduler to run either script daily (or on a schedule that makes sense for your backups)
  3. Double-check paths: Make sure you replace the placeholder paths in both scripts with your actual backups directory location

内容的提问来源于stack exchange,提问作者Richard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:50:00