excel - 通过 VBScript 从主机名列表更新 Excel 连续 ping

标签 excel vbscript ping

以下 VBScript 将显示单个 ping 的状态从主机名列表到 Excel 电子表格的命令:

Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True

objExcel.Workbooks.Add

intRow = 2


'# Define Labels 

objExcel.Cells(1, 1).Value = "Node"

objExcel.Cells(1, 2).Value = "Status"


'# Create file system object for reading the hosts from text file


Set Fso = CreateObject("Scripting.FileSystemObject")

Set InputFile = fso.OpenTextFile("MachineList.Txt")

'# Loop thru the text file till the end 

Do While Not (InputFile.atEndOfStream)

HostName = InputFile.ReadLine

'# Create shell object for Pinging the host machines

Set WshShell = WScript.CreateObject("WScript.Shell")

Ping = WshShell.Run("ping -n 1 " & HostName, 0, True)


objExcel.Cells(intRow, 1).Value = HostName

'# use switch case for checking the machine updown status

Select Case Ping

Case 0
    objExcel.Cells(intRow, 2).Value = "Up"
    objExcel.Cells(intRow, 2).Interior.Color = vbGreen
Case 1
    objExcel.Cells(intRow, 2).Value = "Down"
    objExcel.Cells(intRow, 2).Interior.Color = vbRed

End Select


intRow = intRow + 1

Loop

'# Format the excel

objExcel.Range("A1:B1").Select

objExcel.Selection.Interior.ColorIndex = 19

objExcel.Selection.Font.ColorIndex = 11

objExcel.Selection.Font.Bold = True

objExcel.Cells.EntireColumn.AutoFit

此代码按预期工作。

我想通过 Excel 的实时更新不断地 ping 主机名。我已尝试添加 -t到 ping 命令 - 而不是 -n 1就像您在命令提示符下一样,但是脚本会挂起,因为它将在列表中的第一个主机名处停止,并且不会进一步进行。

我的问题:如何实现连续 ping 命令或重复运行脚本?

在网上搜索了几天的解决方案后,我找不到任何解决方案。

最佳答案

使用 wscript.sleep并将结果写入文本文件

Dim txt, fso, InputFile, OutputFile, arr, h, Ping, sep

Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = wscript.CreateObject("WScript.Shell")

'# load the hosts from a text file into an array
Set InputFile = fso.OpenTextFile("MachineList.Txt")
arr = Split(InputFile.readall(), vbCrLf)
InputFile.Close

Do
    txt = Now & vbcrlf 'add a timestamp
    sep = ""
    For Each h In arr
        Ping = WshShell.Run("ping -n 1 " & h, 0, True)

        txt = txt & sep & h & ","
        If Ping = 1 Then
            txt = txt & "Up"
        ElseIf Ping = 0 Then
            txt = txt & "Down"
        Else
            txt = txt & "???"
        End If
        sep = vbCrLf
    Next 

    Set OutputFile = fso.createTextFile("Results.Txt")
    OutputFile.write txt
    OutputFile.Close

    wscript.sleep 1000 * 60 '60 sec
Loop

关于excel - 通过 VBScript 从主机名列表更新 Excel 连续 ping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818296/

相关文章:

c# - Ping.SendAsync() 始终成功,即使客户端在 cmd 中不可 ping

excel - 计算Excel行中的当前条纹

excel - 从 Excel 打开 Outlook 通讯簿

vba - 以整数形式插入日期 (Excel)

vbscript - 我们如何在 testcomplete 中实现关键字驱动的自动化框架

vbscript - 如何通过 VBscript 获取 CAD 零件的位置?

excel - 在 Excel 中反向汇总数据

datetime - 使用当前区域设置 <> 美国将日期字符串值从美国转换为 native 日期?

php - 错误的 DNS 设置,php_network_getaddresses : getaddrinfo failed Name or service not known, nslookup

ios - 最好的查找方法是我的自定义以太网设备在线以及它为 iOS 获得的 IP 是什么?