Batch Script Arrays - Batch Script

How to create an Array

Note:
  • Each element of the array needs to be defined with the set command.
  • The ‘for’ loop would be required to iterate through the values of the array.
Method 1:
Use the following set command to create an array
Where 0 is the index of the array and 1 is the value assigned to the first element of the array.
Method 2:
Define a list of values and iterate through the list of values as follows.

Output

How to access a value from the Arrays

It can be done using subscript syntax, passing the index of the value you want to retrieve within square brackets immediately after the name of the array as follows.
Here, the index starts from 0 which means the first element can be accessed using index as 0, the second element can be accessed using index as 1 and so on. Here is an example to create, initialize and access arrays −

Output

How to modify an Array

Adding an element to the end of the array
Use the set element along with the last index of the array element.
Example
The above command produces the following output.
Modifying an existing element of an Array
Assign a new value at a given index as shown below −

Output

How to iterate Over an Array

Use the ‘for’ loop and go through each element of the array. The following example shows a simple way that an array can be implemented.
Notes
  • Each element of the array needs to be specifically defined using the set command.
  • The ‘for’ loop with the /L parameter for moving through ranges is used to iterate through the array.

Output

How to do length of an Array

Iterate over the list of values in the array since there is no direct function to determine the number of elements in an array.

Output

How to create Structures in Arrays

Structures can also be implemented in batch files using a little bit of an extra coding for implementation. The following example shows how this can be achieved.
Example
Notes
  • Each variable defined using the set command has 2 values associated with each index of the array.
  • The variable i is set to 0 so that we can loop through the structure will the length of the array which is 3.
  • We always check for the condition on whether the value of i is equal to the value of len and if not, we loop through the code.
  • We are able to access each element of the structure using the obj[%i%] notation.

Output

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Batch Script Topics