Batch file returns "divide by zero error" only when run using Task Scheduler

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:

Marcel

Posted 2016-12-27T02:42:19.307

Reputation: 275

That snippet will not cause a divide by zero error. Where is the rest of your batch file? – DavidPostill – 2016-12-27T13:57:59.227

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 – 2016-12-27T15:07:10.853

Yes, well please [edit] the question and include the complete batch file to make the question complete. – DavidPostill – 2016-12-27T15:21:38.377

Answers

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.

Marcel

Posted 2016-12-27T02:42:19.307

Reputation: 275

1note 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 – 2016-12-27T18:19:20.093