1

I was Wandering How I would Make A batchfile that sets a folder to read-only if it reach Said Size (1GB?)

What I got So Far:

@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

Really My only thing is how do I make it so that when It hits the Limit Set, It uses the attrib string. Also the errorlevels may be horribly messed up, My first time using errorlevels.

  • 1
    Is a batch script [really the best solution](https://4sysops.com/archives/file-server-resource-manager-fsrm-part-3-quota-management/) here? – rojo Feb 22 '16 at 15:13

1 Answers1

0

To get the size of a folder, you need to enumerate all files recursively within and get their sizes. See the rem statements in the code below for an explanation.

@echo off & setlocal enabledelayedexpansion

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

rem // GUI folder chooser
rem // http://stackoverflow.com/a/15885133/1683264
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 // http://stackoverflow.com/a/30894749/1683264
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
rojo
  • 24,000
  • 5
  • 55
  • 101