Quickest way to determine if a remote PC is online

2019-08-06 06:04发布

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条回答
贪生不怕死
2楼-- · 2019-08-06 06:24

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
查看更多
疯言疯语
3楼-- · 2019-08-06 06:34

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
查看更多
登录 后发表回答