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

巧了我就是萌 提交于 2019-12-13 03:18:11

问题


I'm new to bat scripting and I have following requirement to meet:

If Dir eg. C:\test size exceed 50GB, then the script should delete the oldest files until the size of directory goes back to 50GB or little less.

I have modified the below script I found on Get size of a directory in 'MB' using batch file but I'm not sure how to proceed with the remaining requirements. See the small modifications I have done so far and I would appreciate any input:

@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

回答1:


This seems to work on my computer.

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 or 1 Gig.



来源:https://stackoverflow.com/questions/48159497/windows-bat-script-to-get-directory-size-if-over-n-gb-then-delete-oldest-files-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!