Defrag all volumes via vbs and task schedule

I want to be able to use the code below to set a vbs to run in task scheduler to defrag all volumes regardless if the volume needs it or not. Will it work? Or is there other ways scripts to do it? I do not want to buy a third party product.
I have tested this seems to be working. I just need to verify that it defrags regardless if drive needs it or not.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
    & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colVolumes = objWMIService.ExecQuery("Select * from Win32_Volume")
For Each objVolume in colVolumes
     errResult = objVolume.Defrag()

Open in new window

Who is Participating?
Shift-3Connect With a Mentor Commented:
You can do this more easily with a batch script.

Paste the script below into a text file with a .cmd extension.  Running it will defrag all local drives.

@echo off
for /F "tokens=1" %%G in ('wmic logicaldisk get deviceid^,drivetype ^| find "3"') do (
 defrag %%G -f

Open in new window

timothydoerrAuthor Commented:
I have tried (Shift-3) batch file, didnt see it doing anything, changed echo to on and its just scrolling for for /F "tokens=1" %%G in ('wmic logicaldisk get deviceid^,drivetype ^| find "3"') do (
 defrag %%G -f
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.