2
1
I'm trying to figure out how to write a script that will let me arbitrarily assign and remove a secondary IP address to a system. I'm most comfortable with batch scripting, so I'd rather focus on solutions for that, if it's possible.
I'm pretty sure I've figured out how to take user input and use it to configure a new IP address and gateway.
The batch script below is written for an interface named "LAN".
SET /P NEW-IPADDR="Enter IP:"
SET /P NEW-MASK="Enter Subnet Mask:"
SET /P NEW-GW="Enter Gateway:"
netsh interface ip add address name=LAN addr=%NEW-IPADDR% mask=%NEW-MASK% gateway=%NEW-GW% gwmetric=0
PAUSE
The PAUSE
is inserted to allow an opportunity to check for errors in netsh
before the console window automatically exits.
I'm sure the script could use some extra statements for error checking (to work around empty user inputs, or validate that inputs match the pattern of an IP address). But what I'm worried about figuring out right now, is how to clear previously-set secondary IP addresses.
One easy option would be to just set the script to clear all IPs every time, and have a line pre-written that automatically sets up the primary IP before prompting for the secondary. Ideally though, I'd like the script to only be working on secondary IPs.
Option two is to change the last line of the above script to the following:
ECHO "Secondary IP address configured. Press any key to remove secondary IP."
PAUSE
netsh interface ip delete address name=LAN addr=%NEW-IPADDR% gateway=%NEW-GW%
However, that requires trusting that the script will not be abnormally terminated during the PAUSE
. Not exactly something you can really rely upon.
Another option would be to have the script store the secondary IPs that it configures somewhere permanent, so that it can pull the values later and only work with those. It's easy enough to get the values into permanent storage (ECHO "%NEW-IPADDR%" > SecondaryIP.txt && ECHO "%NEW-MASK%" >> SecondaryIP.txt && ECHO "%NEW-GW%" >> SecondaryIP.txt
) but now I have two problems:
- I don't know how to get the data out of that text file, in a way that's usable by the batch script. (I'm sure this can easily be fixed.)
- This relies upon the script being the only thing that touches the secondary IP. A bit more trustworthy than the script exiting normally, but still not quite 100%.
The ideal option would be a script that can recognize a "Primary IP" as opposed to a "Secondary IP" and only work on the latter. Is there a way to do this?
I need a method that's compatible with a standard Windows XP build or later, with little to no usage of third-party tools. Although I'd rather do this in batch, I'm also interested in learning more about PowerShell and it is installed on the systems where I'll be using this. So, PowerShell-based solutions are welcome also.