Monday, January 14, 2013

Arrays in Batch scripts


@if "%_echo%"=="" echo off
setlocal EnableDelayedExpansion
set _BatDir=%~dp0
set _BatchFile=%0
set _StartTime=%TIME%
echo %0 %*

REM Populate Array
for %%G in (c:\temp\*) do (
    set /a count+=1
    call :array_setitem myArray !count! %%~nG
)


REM Read Array
for /L %%X in (1,1,%count%) do (
    call :array_getitem last myArray %%X
    echo myArray[%%X] == !last!
)

goto :EOF

:array_setitem <Array> <Index> <Value>
    echo Set %1[%2] = %3
    set %1[%2]=%3
goto :EOF

:array_getitem <Result> <Array> <Index>
    set array.name=%2
    set array.index=%3
    set outputvar=%1
    for /f "delims=[=] tokens=1,2,3" %%a in ('set %array.name%[') do (
        if %%b==%array.index% set %outputvar%=%%c
    )
goto :eof

No comments:

Post a Comment