Ping script with loop and save in a txt

谁说我不能喝 提交于 2019-12-11 14:27:01

问题


i try to make an Ping script with vbs. I need a Script, that ping (no ping limit, the program will run all the time) a computername in the network every 2 seconds and save the results in a txt file.

For Example:

06/08/2010 - 13:53:22 | The Computer "..." is online

06/08/2010 - 13:53:24 | The Computer "..." is offline

Now i try a little bit:

   strComputer = "TestPC"

    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}")._
     ExecQuery("select * from Win32_PingStatus where address = '"_
     & strComputer & "'")
    For Each objStatus in objPing
     If IsNull(objStatus.StatusCode) Or objStatus.StatusCode <> 0 Then 

    ..........          

    Next

And than i don't know how to make it. (I'm new with vbs :-))

I hope some one can help me.

Greeting, matthias


回答1:


Try this

Option Explicit

Dim strHost, strFile

strHost = "www.google.com" '"127.0.0.1"
strFile = "C:\Test.txt"

PingForever strHost, strFile

Sub PingForever(strHost, outputfile)
    Dim Output, Shell, strCommand, ReturnCode

    Set Output = CreateObject("Scripting.FileSystemObject").OpenTextFile(outputfile, 8, True)
    Set Shell = CreateObject("wscript.shell")
    strCommand = "ping -n 1 -w 300 " & strHost
    While(True)
        ReturnCode = Shell.Run(strCommand, 0, True)     
        If ReturnCode = 0 Then
            Output.WriteLine Date() & " - " & Time & " | The Computer " & strHost & " is online"
        Else
            Output.WriteLine Date() & " - " & Time & " | The Computer " & strHost & " is offline"
        End If
        Wscript.Sleep 2000
    Wend
End Sub



回答2:


You put your pings inside a loop of some kind and then use Wscript.Sleep 2000 to sleep for 2 seconds.

Then you use the File System Object (FSO) to write to a file. Information can be found here.

Edit: Something like this might work:

Const OpenFileForAppending = 8 
Dim fso, ts
Set fso = CreateObject("Scripting. FileSystemObject")

While 1 > 0 ' loop forever      
    Set ts = fso.OpenTextFile("c:\temp\test.txt", OpenFileForAppending, True)

    ' do your pinging code

    'if ok
        ts.WriteLine("OK")
    'else
        ts.WriteLine("Not OK")
    'endif

    ts.Close()
    Wscript.Sleep 2000
Wend


来源:https://stackoverflow.com/questions/2997034/ping-script-with-loop-and-save-in-a-txt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!