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: