Quickest way to determine if a remote PC is online

时间:2015-07-28 15:35:49

标签: vba ping filesystemobject

I tend to run a lot of commands against remote PCs, but I always check to make sure they are online first. I currently use this code:

If objFSO.FolderExists("\\" & strHost & "\c$") Then
    'The PC is online so do your thing

However, when the remote PC is not online, it takes my laptop ~45 seconds before it times out and resolves to FALSE.

Is there a way to hasten the timeout? Or is there another easily implementable solution to determine if a PC is online?

2 个答案:

答案 0 :(得分:3)

You could use WMI to ping it.

Function IsOnline(strHost As String) As Boolean

    Dim strQuery As String
    strQuery = "select * from Win32_PingStatus where Address = '" & strHost & "'"

    Dim colItems As Object
    Set colItems = GetObject("winmgmts://./root/cimv2").ExecQuery(strQuery)

    Dim objItem As Object
    For Each objItem In colItems
        If IsObject(objItem) Then
            If objItem.StatusCode = 0 Then
                IsOnline = True
                Exit Function
            End If
        End If
    Next

End Function

答案 1 :(得分:1)

You can use the return code from a ping request:

Function HostIsOnline(hostname)
    Set oShell     = WScript.CreateObject("WScript.Shell")
    Set oShellExec = oShell.Exec("ping -n 1 " & hostname)

    While oShellExec.Status = 0
        WScript.Sleep(100)
    Wend

    HostIsOnline = (oShellExec.ExitCode = 0)
End Function