问题:要求用脚本完成一个ping通文件所有逐行IP地址,并将结果输出到新的文件中。
版本一:(exec——不显示在cmd页面上,后台操作)
Set WshShell = WScript.CreateObject("WScript.Shell") Set pingShell = WshShell.exec ("cmd /c ping 192.168.1.105") intState = pingShell.StdOut.ReadAll() msgbox intState
'引自其它博客 Const conErr = -2 Function Ping(ByVal Server) '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '过程说明: ' 1) 原型 Ping(ByVal 服务器) ' 2) ErrLevel返回值: ' ' |值 |标志 |描述 ' -1 True 网络畅通 ' 0 False 网络有误 ' -2 conErr 网址为空 ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Dim WshShell, intState, Args If IsEmpty(Server) Then Ping = conErr : Exit Function End If Args = " -n 2" Set WshShell = WScript.CreateObject("WScript.Shell") intState = WshShell.run ("ping.exe " & Server & Args, 4, True) If intState = 0 Then Ping = True Else Ping = False End If Set WshShell = Nothing End Function
WshShell.run ("ping.exe " & Server & Args, 4, True)
WshShell.exec ("cmd /c ping 192.168.1.105")那么可以看到run与exec显然是有差别的,参数个数的问题,详细介绍:
参阅http://www.jb51.net/article/17327.htm
参阅http://demon.tw/programming/vbs-run-and-exec.html
run调用:
参阅http://blog.csdn.net/xiao_cs/article/details/6262144
零碎小问题整理:
1. 打开方式原来有大窍门:用cmd打开那么cmd就默认路径在当前路径下,然后ping命令就不能用了。要不然就是用ping.exe;如果使用WSH打开,那么一切都不是问题。当然这时候输出文件的路径就在系统路径下了,也就是c://windows/system32之类的。
2. windows cmd是可以使用命令将当前指令的结果输出到文件中而不是屏幕上(linux中管道里面常用),指令如下:
ping 192.168.1.105 > info.txt
最后,发一个成品吧!
'引用函数 Const conErr = -2 Function Ping(ByVal Server) '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '过程说明: ' 1) 原型 Ping(ByVal 服务器) ' 2) ErrLevel返回值: ' ' |值 |标志 |描述 ' -1 True 网络畅通 ' 0 False 网络有误 ' -2 conErr 网址为空 ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Dim WshShell, intState, Args If IsEmpty(Server) Then Ping = conErr : Exit Function End If Args = " -n 2" Set WshShell = WScript.CreateObject("WScript.Shell") intState = WshShell.run ("ping.exe " & Server & Args, 4, True) If intState = 0 Then Ping = True Else Ping = False End If Set WshShell = Nothing End Function dim objFSO,objFile,strline Set objFSO = CreateObject("Scripting.FileSystemObject") Set objFile = objFSO.OpenTextFile("in.txt", 1) Currentdate=year(Now)&"-"&Month(Now)&"-"&day(Now) Set writ = objFSO.OpenTextFile("log-"& Currentdate &".txt", 2, true) do until objFile.atendofstream Strline=objFile.readline x = Ping(Strline) 'msgbox Strline & " " & x writ.writeline(Strline & " " & x) loop objFile.close writ.close set objFSO=nothing