Monday, 13 July 2015

VBScript Resolve IP Address to Hostname

In this article, I am going write vbscript code to resolve computer name from IP address and vbscript code to get hostname of multiple IP addresses (from text file) and export its output to CSV file.

Resolve IP Address to Hostname:

The below vbscript code resolves the computer name from given IP address.
Dim ipAddress,hostname
ipAddress = "202.172.1.72"

On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & ipAddress & "\root\cimv2")
  If Err.Number <> 0 Then
    hostname = "Cannot resolve hostname"
    Err.Clear
  Else
   Set colItems = objWMIService.ExecQuery("Select * FROM Win32_ComputerSystem", "WQL", _
     wbemFlagReturnImmediately + wbemFlagForwardOnly)
   For Each objItem In colItems
     hostname = objItem.Name
   Next
  End If

WScript.Echo "Resolved computer name : '" & hostname & "'"

Get Hostname for set of IP addresses and Export to CSV:

Use the below vbscript code to resolve machine name for multiple IP addresses and export output into csv file. First create the text file IP-Addresses.txt which includes one IP address in each line. You will get the computer name and IP address list in the csv file HostNames.csv.
Dim ipaddressTxtFile,outCSVFile
Dim csvColumns,ipAddress,hostname
Const ForReading = 1

'Create CSV file 
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
outCSVFile ="C:\HostNames.csv"
Set objCSVFile = objFSO.CreateTextFile(outCSVFile, _ 
    ForWriting, True)
'Write comma delimited list of columns in CSV output file.
csvColumns = "IPAddress,HostName"
objCSVFile.Write csvColumns
objCSVFile.Writeline

'Set path of text file which contains set of IP Addresses (one ip address per line).
ipaddressTxtFile = "C:\IP-Addresses.txt"
' Open the file for reading.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(ipaddressTxtFile, ForReading)

' Read the IP addresses from text file and find its computer name.
Do Until objFile.AtEndOfStream
' Read IP address
ipAddress = objFile.ReadLine

On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & ipAddress & "\root\cimv2")
  If Err.Number <> 0 Then
    hostname = "Cannot resolve hostname"
    Err.Clear
  Else
   Set colItems = objWMIService.ExecQuery("Select * FROM Win32_ComputerSystem", "WQL", _
     wbemFlagReturnImmediately + wbemFlagForwardOnly)
   For Each objItem In colItems
     hostname = objItem.Name
   Next
  End If

'Write IP address and computer name into CSV file
objCSVFile.Write ipAddress & "," 
objCSVFile.Write hostname & ""
objCSVFile.Writeline

Loop
Note: If you open the csv file using MS Excel, the line should comes in a single cell, to fix this issue, copy the content of the csv file and paste in new text file and save it as new .csv file.

Advertisements
Advertisements

No comments:

Post a Comment