How Can I Read in IP Addresses and Use Them in a Script?
Hey, Scripting Guy! I have a text file that contains a bunch of IP addresses. I’d like to be able to read these addresses from a script, and then use them to connect to those computers. Is that possible?
Hey, RL. You bet you can do this, and here’s how. First, make sure your text file looks something like this, with each IP address on a single line:
192.168.1.1 192.168.1.2 192.168.1.3 192.168.1.4
Next, you need a script that can read the text file line-by-line, storing the IP address in a variable as it goes. Here’s a sample script that reads a file named C:\Addresses.txt, and simply echoes back each value read:
Const ForReading = 1 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile _ ("c:\Addresses.txt", ForReading) Do Until objTextFile.AtEndOfStream strComputer = objTextFile.Readline Wscript.Echo strComputer Loop
As you can see, we open the file, then use a Do Until loop to read each line of code. The Do Until loop will read a line of code (using the ReadLine method), store that value in the variable strComputer, and then echo back the value (and because each line in the text file consists of a single IP address, each value echoed back will be a single IP address). The script then loops around and reads the next line of code, automatically repeating this process until there are no more lines left to read (in other words, it keeps going until the AtEndOfStream property is True).
All we have to do now is replace the line of code that echoes back the IP address with some code that does something more useful. In our example, we’re going to retrieve the name of the operating system installed on each computer whose IP address is found in the text file. This is easy to do, because WMI allows you to connect to computer using IP addresses, like so:
strComputer = GetObject("192.168.1.1")
That’s what we’re going to do here; the only difference is that instead of hard-coding in the IP address we’ll use the variable strComputer to represent the IP address. Because the value of strComputer changes each time the loop runs (because each time we read in a new IP address from the text file), over the course of the script we’ll end up connecting to – and retrieving information from – each computer in the text file:
Const ForReading = 1 Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTextFile = objFSO.OpenTextFile _ ("c:\Addresses.txt", ForReading) Do Until objTextFile.AtEndOfStream strComputer = objTextFile.Readline Set objWMIService = GetObject _ ("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery _ ("SELECT * FROM WIN32_OperatingSystem") For Each objItem in colItems Wscript.Echo objItem.Caption Next Loop
Much easier than you thought it would be, right?