开发者

VBS: Check IP address and open URL (but only once)

开发者 https://www.devze.com 2023-01-16 00:57 出处:网络
I\'m trying to create a VBScript which will detect if the computer it is being run on is connected to our LAN at work by checking its IPv4 address (assigned by DHCP) and then open a specific URL depen

I'm trying to create a VBScript which will detect if the computer it is being run on is connected to our LAN at work by checking its IPv4 address (assigned by DHCP) and then open a specific URL depending upon whether it is inside or outside our network. The script will be mainly used on lap开发者_如何转开发tops which will roam between work (10.12.90.0/22) and home (usually 192.168/23, but this could be anything really). In both cases I need to open the corect URL only once, because there will almost always be more than one network adapter (wired/wireless/bluetooth etc.).

The script below appears to work when I tested it, but not being a programmer I am not sure if there is a better way to do this. Ideally, I would like to avoid pinging servers because of the delay.

strComputer = "."

strInternal = "http://intranet/"
strExternal = "http://www.mydomain.com/"

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery _
    ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled = True",,48)

For Each objItem in colItems
    strIPAddress = objItem.IPAddress(0)
    arrIPAddress = Split(strIPAddress, ".")

    If (arrIPAddress(0) = "10") And (arrIPAddress(1) = "12") Then
        ipChecked = 1
        Run strInternal
    Else
        If ipChecked = 1 Then
            WScript.Sleep(10)
        Else
            ipChecked = 1
            Run strExternal
        End If
    End If

Next

Sub Run(ByVal sFile)
Dim shell
    Set shell = CreateObject("WScript.Shell")
    shell.Run Chr(34) & sFile & Chr(34), 1, false
    Set shell = Nothing
End Sub


How about checking to see if the internal website is available, load it if it is else load the public website? You could use a function like this:

Function UrlExists(xURL)
    On Error Resume Next
    Err.Clear
    Dim objXML

    Set objXML = CreateObject("Microsoft.XMLHTTP")
    objXML.Open "HEAD",xURL,False
    objXML.Send

    If Err.Number <> 0 Or objXML.Status <> 200 Then
        UrlExists = False
    Else
        UrlExists = True
    End If
    Set objXML = Nothing
End Function

and then call it from your main script:

strInternal = "http://intranet/default.htm"       
strExternal = "http://www.mydomain.com/"  

If URLExists(strInternal) Then
 Run strInternal
Else
 Run strExternal 
End If  
0

精彩评论

暂无评论...
验证码 换一张
取 消