Search code examples
listvariablesbatch-fileping

Linking an String variable into an IP in batch


I would like to know if I can create a list where I have a number of IPs, each is associated with a name. e.g. server1 = 10.40.90.1, server2 = 10.20.10.1, etc.

This way when I execute the file, it asks me to put in the server name, for pinging, instead of the IP. Then output only the name, and percentage of packets lost.

I know how to create a list, and use it, in a batch file, but I'm not sure how to make the IP's into variables.


Solution

  • Batch files are kind of under-powered for this kind of thing so the techniques are often strange. But, you can use set after setlocal to set local variables for the servers' IP addresses. Then you can assign the address to the IP address associated with the provided server name using call set and the triple %%% syntax to replace the provided server name with the value of the variable it refers to.

    @echo off
    setlocal
    set "server1=10.40.90.1"
    set "server2=10.20.10.1"
    
    set /p "server_name=Enter the server name: "
    call set "ip_address=%%%server_name%%%"
    echo %ip_address%
    
    REM TODO: ping %ip_address% and parse output
    
    endlocal