Open In App

Batch Script – Creating Structures in Arrays

Last Updated : 04 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we’ll understand how to create structures in arrays in a batch script. 

What are Structures?

Structures are like a multi-type list of values, unlike arrays we have a list of single type values. Let’s say we have an array called person, we have initially declared to a list of names, but if we want to add age, phone number, or gender, we need to create separate arrays to contain them and carefully index them as per the name in the initial array. By creating structures in arrays, we can create multiple lists like structures in a single array.  

How to create Structures using Arrays?

To create a structure in an array, we need to create the list similarly but by adding the dot [.] operator along with the identifier to each of the elements. 

We can define easily define structures in an array by defining the index prefixed with the name of the component with a dot operator.

arr_name[index].comp_name=value

Let’s take an example of a structure of a person, we can have components/keys like name, age, gender, etc. We can create the array elements and their keys one by one. 

@echo off

set struct[0].name=John 
set struct[0].age=12 
set struct[0].gender="M"
set struct[1].name=Kevin 
set struct[1].age=20 
set struct[1].gender="M"
set struct[2].name=Jessie
set struct[2].age=15 
set struct[2].gender="F"
FOR /L %%i IN (0 1 2) DO  (
   call echo Name: %%struct[%%i].name%%, Age:^
    %%struct[%%i].age%%, Gender:, %%struct[%%i].^
    gender%%
) 

So from the above code, we can see that we have created a structure from a single array. We have different types of variables like string, integer, and character. These structures in the form of arrays can be retrieved by dot prefixing the name of the components in the structure with the list. That is in this example, we have used %%struct[%%i].name%% for accessing the name of the ith element in the array struct, the .name%% is the identifier for the name component in the structure. 

We can extend this further to create customized structures with multiple types and components in a form of a list. This is how we can create structures in BAtch scripts.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads