Last Updated: February 25, 2016
·
1.941K
· 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
cls
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)

goto:end

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

:reverseArrayX
if "%reverseArray%"=="" (set reverseArray=%1) else (set reverseArray=%1, %reverseArray%)
@goto:eof

:outputElement
echo. - %~1
@goto:eof

:hardError
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

:end
Echo.Completed
exit /b         &::should happen anyway but this makes it explicit