How-to: Create and use Arrays (pseudo-arrays) in Windows CMD.

Unlike PowerShell, which fully supports arrays, there is no built in support for array variables within the CMD shell. However with some effort you can replicate this functionality using a series of separate variables, named to represent the array:

Set elem[1]=First element
Set elem[2]=Second one
Set elem[3]=The third one

To perform array indexing operations with these, use EnableDelayedExpansion and a reference like !elem[%var%]!
this is explained fully in this StackOverflow Q/A.

Example of building and then reading an array of values:

@echo off
Setlocal EnableDelayedExpansion

Set _folder=c:\pictures
Set _count=1

:: Store each filename in a pseudo-array named like "_pic[0], _pic[1]..."
For /r "%_folder%" %%A in (*.jpg) do (
   Set _pic[!_count!]=%%~A
   Set /a _count+=1
Set /a _count-=1
Echo The number of files is %_count%

Echo Now enumerating the array:
For /L %%G in (1,1,%_count%) Do (
Echo Array item _pic[%%G] is !_pic[%%G]!

Credits: bluesxman, adapted from this forum thread: Pick random file from a folder.

"There are only two hard things in Computer Science: cache invalidation and naming thingsā€ ~ Phil Karlton

Related commands

How-to: Variables and Operators - Create variable, add to value, subtract, divide.
How-to: Environment variables - Windows environment variables Env:
How-to: Functions - How to package blocks of code.
PowerShell equivalent: Create and use PowerShell Arrays

Copyright © 1999-2024
Some rights reserved