Search code examples
batch-filewmic

How to passing in array parameter in windows batch?


I'm trying to run this command in batch file:

wmic nicconfig where macaddress=somemacaddr call SetDNSServerSearchOrder (an array paramter)

For example:

set dnslist[1]="172.12.3.1"
set dnslist[2]="222.123.2.1"
...
set dnslist[x]="135.132.1.2"

We don't know the dnslist size before running the batch. How could we passing the dnslist to SetDNSServerSearchOrder directly?


Solution

  • There are no arrays in batch files, per se. What you have there is just a collection of environment variables with the same prefix. There's nothing special about that.

    How to pass them to a command depends on the command (e.g. are they space-separated, i.e. individual arguments, or comma-separated, or something else entirely?). You need to create a string from those variables that matches the format the program expects, e.g. when they should be space-separated, create a string the following way:

    setlocal enabledelayedexpansion
    for /f "delims==" %%A in ('set dnslist[') do set List=!List! %%B
    
    wmic nicconfig where macaddress=somemacaddr call SetDNSServerSearchOrder %List%
    

    Likewise for different delimiters. Delayed expansion should ideally be enabled at the very start of your script; no use creating a new local environment in the middle of it, usually.

    If you want to call the command once for every entry in your "list", you don't need to create the delimiter-separated list in the first place, but rather just call the command directly with the entry.