1.

Solve : Auto defrag BAT file when fragmentation is above 5%?

Answer»

Is there a way to parse the -a switch response of DEFRAG to determine the level of fragmentation and if it is above a certain amount start DEFRAG c:.Yes. Parsing is easy

Code: [Select]@echo off
set vol=c:
for /f "tokens=1-9 delims=%% " %%A in ('defrag %vol% -a ^| find "Fragmented"') do set /a fraglevel=%%I
echo Volume %vol% is %fraglevel% percent fragmented
IF %fraglevel% GTR %whatever% defrag -blah blah blah
Thanks Dias - that worked. I don't do this for living so I can get into tro ;Duble very easily. Dias,

Would you please, explain briefly the code for me?

for /f "tokens=1-9
Why 1-9?

delims=%%
Why %%?

" %%A in ('defrag %vol% -a ^| find "Fragmented"')What is difference between using only "|" vs. "^|"?

do set /a fraglevel=%%I
Where does %%I come from? (can it be any other character or
it has to be "I"?

Thanks,
Geza

Quote from: Geza on August 16, 2008, 11:43:42 PM

Would you please, explain briefly the code for me?

I will do so briefly, but really you need to to study the "tokens=" and "delims=" features in FOR /F.

Type FOR /? at the prompt. Also search the web for guidance.

Quote
for /f "tokens=1-9 Why 1-9?

Because by selecting spaces and percent signs as token delimiters the defragmentation percentage figure is the 9th token in the output line of defrag which contains the figures, (the line which contains the word Fragmented which is selected by Find.exe)


A B C D E F G H I
1 2 3 4 5 6 7 8 9
25.49 GB Total, 10.25 GB (40%) Free, 6% Fragmented (13% file fragmentation)


"Tokens=1-9" FOLLOWED by "%%A in" means "set up 1 explicit loop variable (%%A) and 8 implicit ones (%%B to %%I)"

Quote
delims=%% Why %%?

Because to echo a single percent SIGN in a batch file you have to type %%

Quote
What is difference between using only "|" vs. "^|"?

Just using | in that place would result in a message "| was not expected at this time." The pipe character | needs to be escaped with a caret.

Quote
Where does %%I come from? (can it be any other character or it has to be "I"?

It has to be I. See my chart of tokens above. I chose %%A to be my first token, and I require to extract the 9th token, and I is the 9th LETTER of the Roman alphabet.


Dias,

Thank you for the explanation, it was very clear.
I LEARNED a lot more from it than by just typing "For /?" which is a typical Microsoft help, it does gives you an ANSWER but by itself it is useless.

Thanks!
Geza


Discussion

No Comment Found