0

I had an issue with a batch file that returned "Divide by zero error" if, and only if, it was run using Task Scheduler. If run manually, it behaved as expected.

I had managed to narrow down the problem to the following code snippet, which returned 0 when run from Task Scheduler, and then caused division by zero.

SET numfiles=0
FOR %%x in (*.jpg) DO SET /a numfiles+=1

SET /a rand=%RANDOM% %%numfiles%
SET /a selected=%rand%+1

After an hour of tearing my hair out, I found a solution which, while logical, was certainly not the first thing I thought of. Therefore, I'm sharing my solution:

  • That snippet will not cause a divide by zero error. Where is the rest of your batch file? – DavidPostill Dec 27 '16 at 13:57
  • The snippet returned 0, as there were no .jpg files in System32. The next operation was finding a random number between 1 and numfiles (inclusive), leading to modulo division by zero. – Marcel Dec 27 '16 at 15:07
  • Yes, well please edit the question and include the complete batch file to make the question complete. – DavidPostill Dec 27 '16 at 15:21
1

The issue turned out to be that Task Scheduler does not run batch files from their own directories, but from System32. Hence, the problem is easily solved by adding

cd [relevant path]

to the beginning of the script.

Hopefully, I managed to save someone else from having to go through the same frustrating steps.

  • 1
    note the real answer is to test (and validate) your variables before using them, especially when renaming files, you can thrash a whole directory this way. – Yorik Dec 27 '16 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.