检查是否在VB脚本中建立了网络连接

时间:2018-04-25 10:27:33

标签: vbscript

下面的代码是检查机器上的网络连接是否已建立。

Dim T = 0

While(T = 0)

    Set Http = WScript.CreateObject("MSXML2.ServerXMLHTTP")
    Http.Open "GET", "http://www.google.com/", True
    Http.Send

        If(Http.Status = 200) Then 
           MsgBox "Network Connection is established"

           T = 1

        else 
           MsgBox "Network Connection isn't established yet"

        End If
Wend

无论网络是否已连接, Http.Status 都会返回值 200 。 任何人都可以帮助我在这里找不到任何东西。

1 个答案:

答案 0 :(得分:0)

参考这个==> Loop a function?

您可以使用以下代码轻松完成此操作:

Option Explicit
Dim MyLoop,strComputer,objPing,objStatus
MyLoop = True
While MyLoop = True
    strComputer = "smtp.gmail.com"
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
    ("select * from Win32_PingStatus where address = '" & strComputer & "'")
    For Each objStatus in objPing
        If objStatus.Statuscode = 0 Then
            MyLoop = False
            Call MyProgram()
            wscript.quit
        End If
    Next
    Pause(10) 'To sleep for 10 secondes
Wend
'**********************************************************************************************
 Sub Pause(NSeconds)
    Wscript.Sleep(NSeconds*1000)
 End Sub
'**********************************************************************************************
Sub MyProgram()
Dim WshShell
set WshShell = WScript.CreateObject("WScript.Shell")         
On Error Resume Next
   With WScript.CreateObject ("InternetExplorer.Application")     
      .Navigate "http://www.example.com/slideshow"
      .fullscreen = 1   
      .Visible    = 1
      WScript.Sleep 10000
   End With    
On Error Goto 0
End Sub
'**********************************************************************************************

编辑:

Wscript.echo(CheckConnection("https://www.google.com"))
'----------------------------------------------------
Function CheckConnection(URL)
    On Error Resume Next 'swallow errors
    Set o = CreateObject("MSXML2.XMLHTTP") 
    o.open "GET",URL, False 
    o.send 
    If Err.Number <> 0 Then
        CheckConnection = "An error occured. Data not retrieved."
'or whatever else you want to do in such a case.
    Else
        CheckConnection = "You are connected"
    End If
    On Error Goto 0 'back to normal error behaviour
End Function
'----------------------------------------------------