Windows 用于获取目录大小的 bat 脚本,如果超过 N GB,则删除最旧的文件以恢复 space

Windows bat script to get directory size if over N GB then delete oldest files to recover space

我是 bat 脚本的新手,我需要满足以下要求:

如果目录,例如。 C:\test 大小超过 50GB,那么脚本应该删除最旧的文件,直到目录大小回到 50GB 或更少。

我修改了在 上找到的以下脚本,但我不确定如何处理剩余的要求。看看我到目前为止所做的小修改,如果有任何意见,我将不胜感激:

@echo off
set limit="50.0"
set Folder="C:\test"
echo The size of %Folder% is 
Call :GetSize %Folder%
IF /I "Call :GetSize %Folder%" GEQ "50.0" Echo Overlimit
<Here I would like to delete oldest zip files until the folder size is back to <=50.0GB>


pause
:GetSize
(
echo wscript.echo GetSize("%~1"^)
echo Function GetSize(MyFolder^)
echo    Set fso = CreateObject("Scripting.FileSystemObject"^)
echo    Set objFolder= fso.GetFolder(MyFolder^)  
echo    GetSize = FormatSize(objFolder.Size^)
echo End Function
echo '*******************************************************************
echo 'Function to format a number into typical size scales
echo Function FormatSize(iSize^)
echo    aLabel = Array("bytes", "KB", "MB", "GB", "TB"^)
echo    For i = 0 to 4
echo        If iSize ^> 1024 Then
echo            iSize = iSize / 1024
echo        Else
echo            Exit For
echo        End If
echo    Next
echo    FormatSize = Round(iSize,2^)
echo End Function
echo '*******************************************************************
)>%tmp%\Size.vbs
Cscript /NoLogo %tmp%\Size.vbs
Del %tmp%\Size.vbs
Exit /b

这似乎适用于我的电脑。

Set fso = CreateObject("Scripting.FileSystemObject")
Set F = fso.GetFolder("C:\Users\User\Desktop\New Folder\Stories\Test")

If F.size > 2^30*2 Then

            'Comments on a stupid editor that can't handle tabs
            'Creating an in memory disconnected recordset to sort files by date
        Set rs = CreateObject("ADODB.Recordset")
        With rs
            .Fields.Append "Date", 7 
            .Fields.Append "Txt", 201, 5000 
            .Open

            For Each Thing in f.files
                .AddNew
                .Fields("Date").value = thing.datelastmodified
                .Fields("Txt").value = thing.path
                .UpDate
            Next
            .Sort = "Date Desc"
            Do While not .EOF
                fso.deletefile  .Fields("Txt").Value
                If f.size < 2^30*2 then Exit Do
                .MoveNext
            Loop
        End With
End If

PS 2^30 = 1 GiByte 或 1 Gig。