To set and also expand a variable inside a code block with parentheses (such as a FOR loop or extended IF block) you need to use delayed expansion.
1. Precede code section (or entire batch) with setlocal enabledelayedexpansion
2. Use exclamation marks, not percent signs, with variable i.e. !errorlevel! not %errorlevel%