批处理文件大小限制器

Batch File Size Limiter

我在想如何制作一个批处理文件,当文件夹达到指定大小(1GB?)时将其设置为只读

到目前为止我得到了什么:

@echo off
color 0b
set /p slimit=Set Max file size:
set /p location=Folder Directory:
cls
color 0a
:loop





echo Limiting File "%location%" at %slimit%.
ATTRIB +R %location% /sd | if errorlevel 1 goto :next1
:next1




echo Limiting File "%location%" at %slimit%..
ATTRIB +R %location% /sd | if errorlevel 1 goto :next2
:next2




echo Limiting File "%location%" at %slimit%...
ATTRIB +R %location% /sd | if errorlevel 1 goto :next3
:next3



goto :loop

真的 我唯一要做的就是如何让它达到限制集时,它使用 attrib 字符串。错误级别也可能一团糟,我第一次使用错误级别。

要获取文件夹的大小,您需要递归枚举其中的所有文件并获取它们的大小。有关解释,请参见下面代码中的 rem 语句。

@echo off & setlocal enabledelayedexpansion

set /a "sizelimit = 1 << 30" & rem // 1GB

rem // GUI folder chooser
rem // 
set "psCommand="(new-object -COM 'Shell.Application')^
.BrowseForFolder(0,'Please choose a folder.',0,0).self.path""
for /f "usebackq delims=" %%I in (`powershell %psCommand%`) do set "folder=%%I"

if not defined folder goto :EOF

rem // get volume blocksize to determine each file's size on disk later
rem // 
for %%I in ("%folder%") do for /f %%J in (
    'wmic volume where "driveletter='%%~dI'" get blocksize /value'
) do 2>nul set /a %%J

set /P "=Enumerating files in %folder%... "<NUL

rem // use "/a:-d" switch to specify *all* files, including hidden and system
for /f "delims=" %%I in ('dir /s /b /a:-d "%folder%"') do (

    rem // check individual file to avoid math exceeding 32-bits
    if %%~zI geq !sizelimit! goto readOnly

    set /a "sizelimit -= ((%%~zI - 1) / blocksize + 1) * blocksize"
)

echo Size limit not exceeded.
goto :EOF

:readOnly
echo Setting to read-only.
attrib +r "%folder%" /sd