Developer42

2013-06-05

Reverse an Array in a Windows Batch File

Filed under: Technology — Tags: , , , , , — Developer42 @ 17:58

The below script demonstrates how to reverse the order of elements in an array in a Windows batch file.

@echo off
cls
echo Script Started
setlocal enableextensions
setlocal enabledelayedexpansion

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

:end
Echo.Completed

Create a free website or blog at WordPress.com.

%d bloggers like this: