Reputation: 11830
I need a batch batch script that checks the size of a folder. If it reaches some X GB, for eg : 10 GB, it should go and delete all the sub directories or files inside it.
I know this would be simple job to do in Linux. But I am quite unfamiliar with windows servers and writing batch scripts.
At the moment I am running a script that deletes files/folder every time it runs, something like this
set folder="C:\myfolder"
cd /d %folder%
for /F "delims=" %%i in ('dir /b') do (rmdir "%%i" /s/q || del "%%i" /s/q)
But I want to delete files/folders only if it reaches some GB size for eg 10 or 12 gb.
Upvotes: 4
Views: 1831
Reputation: 70923
For a batch solution
@echo off
setlocal enableextensions disabledelayedexpansion
rem 12345678901234567890
set "pad= "
for %%a in ("%~f1.") do set "target=%%~fa"
set "limit=%~2"
if not defined limit set "limit=10737418240"
echo(Searching in [%target%] ....
for /f "tokens=3" %%a in ('
dir /s /-c /a "%target%"
^| findstr /i /r /c:"^ .*bytes$"
') do set "size=%%a"
set "limit=%pad%%limit%"
set "size=%pad%%size%"
echo(
echo(.... limit [%limit:~-20%]
echo(.... size [%size:~-20%]
echo(
if "%size:~-20%" lss "%limit:~-20%" (
echo Size is in range
goto :eof
)
echo(Size is out of range. Cleaning ....
pushd "%target%" && (
rem rmdir . /s /q
popd
)
This batch file uses two arguments: the first one is the folder to process (by default the current folder) and the second one the size limit to check (by default 10GB).
A dir
command in used to retrieve the full size under the indicated folder. The ouput from this comand is parsed with a for /f
to get the needed data.
Batch files arithmetic is limited to a 2^31 max value. To handle greater values in conditions, the numbers need to be converted to padded strings to be compared.
The script only echoes information to console. You will need to uncomment the rmdir
command that should remove the contents of the target folder.
Upvotes: 1
Reputation:
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
'make a new folder to delete
Set f = fso.CreateFolder("c:\New Folder")
'wait 30 secs to you can see it in explorer
wscript.sleep 30000
'Checking size
Set fldr = fso.GetFolder("c:\new folder")
Msgbox fldr.size
If fldr.size > 100000000000 then msgbox "too large"
fldr.delete
VBScript is designed for this.
Upvotes: 0
Reputation: 33193
On Windows server use powershell. Finding the size of a folder is then:
$size = (Get-ChildItem $FolderName -Recurse | Measure-Object -Property Length -Sum).Sum
if ($size > $Limit) {
Remove-Item $FolderName -Recurse -Whatif
}
There is a really good explanation of why powershell is potentially more useful than a set of unix tools as the best answer for Is PowerShell ready to replace my Cygwin shell on Windows?
The -Whatif
makes the Remove-Item
safe as adding -WhatIf just reports what the command would do if executed.
Upvotes: 1