Last Updated: February 25, 2016
· johnlbevan

Reverse an Array in Windows Batch

The below code shows how to reverse the order of elements in a windows batch file's array:

@echo off
echo Script Started
verify badvalue 2> nul
setlocal enableextensions enabledelayedexpansion
if errorlevel 1 call:hardError "Unable to enable command extensions."

set arrayTest=("1", "2", "3", "test")

echo.Forward: %arrayTest%
for %%1 in %arrayTest% do (call:outputElement %%1)

call:reverseArray %arrayTest%

echo.Backward: %reverseArray%
for %%1 in %reverseArray% do (call:outputElement %%1)


set reverseArray=
for %%1 in %* do (call:reverseArrayX %%1)
set reverseArray=(%reverseArray%)

if "%reverseArray%"=="" (set reverseArray=%1) else (set reverseArray=%1, %reverseArray%)

echo. - %~1

echo.ERROR: %*  &::display all exception information (allows multiple parameters to be passed / displays them all to ensure flexibility)
pause           &::whilst testing keep this enabled ::todo: remove after testing
exit            &::ensure we don't go forwards after a hard error - nb this will terminate the current console window

exit /b         &::should happen anyway but this makes it explicit