This week we have a question from Vladimir:
Happy New year to you and all the best in the new 2012.
I’m battling here with fragmentation disk problems and I’m wondering;
Is there a way to run a defragmentation process during night hours when all machines are idling? Can it be scripted so you can add it to a scheduler task?”
Yes…we could just go through the manual steps of creating this scheduled task, but Vladimir wants to know if we can easily script it.
The answer is a definite yes. In fact, it is easier to script this than to suffer through all of the windows and settings of the task scheduler.
To add a scheduled task, you just need to call it like this from the command line:
Now, of course that needs some more options.
We want it to run only when the computer is idle, and since we want it to run after hours, we want to rule out lunch…so lets tell it to only run after two hours of inactivity.
Here are the options we will need:
/tr = The path to the application to run
/tn = The name of the task
/ru = User to run the task as
/sc = When to run the task
/i = The number of idle minutes to wait
This is what our command to add the task would look like:
schtasks /create /ru system /sc onidle /i 120 /tn Defrag /tr "%systemroot%\system32\defrag.exe c:"
This command line can be translated to:
Create a task named ‘Defrag’ that will run the defrag program under the system account – only when the computer has been idle for 120 minutes
After you run the task, it will add it:
You can verify by browsing over to scheduled tasks:
That is all there is to it. Now when the system is idle for more than two hours, it will start a defrag of the c drive. This syntax works on Windows XP through Windows 7 / 2008.
One more thing…Subscribe to my newsletter and get 11 free network administrator tools, plus a 30 page user guide so you can get the most out of them. Click Here to get your free tools