VBScript – Return Gateway Address; Site-Aware

email me

This script returns the user’s gateway IP address, locates address in a text file, which then ties it to a location code or name. This is great for making site-aware scripts and packages.

ON ERROR RESUME NEXT

CONST ForReading = 1 

DIM lineInput, IP_Address, workingLine, IPGateway, SiteLocation
DIM objFSO, objFile, objOutput, dataLine, RegCommand, objShell

SET objShell = CreateObject("Wscript.Shell")
SET objFSO = createobject("Scripting.FileSystemObject")

'SETS CURRENT DIRECTORY TO VARIABLE
strCurrentDirectory = objShell.CurrentDirectory

'CLEAR SESSION
dataLine = "" 

'READ FROM GATEWAYS FILE. 
'opens gateways file for reading
SET objFile = objFSO.openTextFile(strCurrentDirectory & "\Gateways.txt", ForReading) 
'Example of text file: gateway address,site code or name
'0.0.0.0,VPN
'11.11.11.254,991
'12.11.11.254,992
'13.11.11.254,Florida

'RETURN GATEWAY ADDRESS USING A FUNCTION
IP_Address = ReturnGateway()

'RETURN LOCATION NUMBER
DO UNTIL objFile.atEndOfStream 	
ON ERROR RESUME NEXT
	dataLine = objFile.readLine & vbCrLf
	IF inStr(dataLine, IP_Address) THEN
	   lineInput = Split(dataLine, ",")
	   workingLine = dataLine	   
	   IPGateway = lineInput(0)	   
	   SiteLocation = lineInput(1)     	   
	   EXIT DO
	 END IF	 
LOOP
'close file for reading
objFile.Close


'IMPORT LOCATION INTO REG KEY
'Location
IF SiteLocation = "" THEN  SiteLocation = "Unknown"
RegCommand = "reg add hkcu\SOFTWARE\MYINFO /v SiteLocation /t REG_SZ /d " & SiteLocation & " /f /reg:64"
objShell.Run RegCommand,0,TRUE'applies reg key

'IP FUNCTION - WILL RETURN GATEWAY ADDRESS
FUNCTION ReturnGateway()
  ON ERROR RESUME NEXT
  DIM ws : SET ws = CreateObject("WScript.Shell")
  DIM fso : SET fso = CreateObject("Scripting.FileSystemObject")
  DIM TmpFile : TmpFile = fso.GetSpecialFolder(2) & "/ip.txt"
  DIM gatewayLine, IP, ReturnIPAddress
  IF ws.Environment("SYSTEM")("OS") <> "" THEN     
    ws.run "%comspec% /c ipconfig > " & TmpFile, 0, True
  END IF
  WITH fso.GetFile(TmpFile).OpenAsTextStream
    DO WHILE NOT .AtEndOfStream
      gatewayLine = .ReadLine
      IF InStr(gatewayLine, "Default Gateway") <> 0 THEN  IP = Mid(gatewayLine, InStr(gatewayLine, ":") + 2)
	  IF IP  <> "" THEN  
	     ReturnGateway = IP
		 EXIT FUNCTION'forces exit upon finding first gateway
	  END IF
    Loop
    .Close
  End WITH
  IF IP <> "::" Then
    IF Asc(Right(IP, 1)) = 13 THEN  IP = Left(IP, Len(IP) - 1)
  END IF
  ReturnGateway = IP  
  fso.GetFile(TmpFile).Delete  
  SET fso = Nothing
  SET ws = Nothing
End Function

Wscript.Quit(0)