通过 VBScript 从主机名列表中持续 ping 更新 Excel

问题描述 投票:0回答:1

以下 VBScript 将显示从主机名列表到 Excel 电子表格的单个

ping
命令的状态:

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 命令或重复运行脚本?

在网上找了好几天的解决办法,都没有找到。

excel vbscript ping
1个回答
1
投票

使用

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
© www.soinside.com 2019 - 2024. All rights reserved.