2014-02-05 33 views
0

我正在嘗試編寫一個腳本來顯示我放入文本文件的每個服務器ip地址。我一直在網上查找並看到下面的腳本。我需要的不是它顯示'在線'我需要它顯示在文本文件中顯示每個服務器的實際IP地址。我一直在尋找這個問題的答案,現在我對vbs很有新意,所以如果下面的腳本錯誤或者簡單,我很抱歉。這確實打開了一個我很滿意的excel文檔。從Ping命令獲取IP地址的VB腳本

Set objExcel = CreateObject("Excel.Application") 
objExcel.Visible = True 
objExcel.Workbooks.Add 
intRow = 2 

objExcel.Cells(1, 1).Value = "Server Name" 
objExcel.Cells(1, 2).Value = "IP Address" 

Set Fso = CreateObject("Scripting.FileSystemObject") 
Set InputFile = fso.OpenTextFile("MachineList.Txt") 

Do While Not (InputFile.atEndOfStream) 
HostName = InputFile.ReadLine 

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

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

Select Case Ping 
Case 0 objExcel.Cells(intRow, 2).Value = "On Line" 
Case 1 objExcel.Cells(intRow, 2).Value = "Off Line" 
End Select 

intRow = intRow + 1 
Loop 

objExcel.Range("A1:B1").Select 
objExcel.Selection.Interior.ColorIndex = 19 
objExcel.Selection.Font.ColorIndex = 11 
objExcel.Selection.Font.Bold = True 
objExcel.Cells.EntireColumn.AutoFit 

回答

0

編輯是因爲我原來的陳述不準確。您可以得到exec推出這樣一個過程的標準輸出:

Option Explicit 

Const HOST_FILE = "MachineList.txt" 

Dim shl, exe, exl, fso, file 
Dim iRow, out, host 

Set shl = CreateObject("WScript.Shell") 
Set fso = CreateObject("Scripting.FilesystemObject") 
Set exl = CreateObject("Excel.Application") 

exl.Workbooks.Add 
iRow = 2 
exl.Cells(1,1).Value = "Server Name" 
exl.Cells(1,2).Value = "IP Address" 

Set file = fso.OpenTextFile(HOST_FILE) 

While not file.AtEndOfStream 
    host = Trim(file.ReadLine) 

    exl.Cells(iRow,1).Value = host 

    Set exe = shl.Exec("%COMSPEC% /c ping -n 1 """ & host & """ | Find ""statistics for""") 

    If Not exe.StdOut.AtEndOfStream Then 
    out = exe.StdOut.ReadAll 
    exl.Cells(iRow,2).Value = getIP(out) 
    Else 
    exl.Cells(iRow,2).Value = "Ping Failed" 
    End If 

    iRow = iRow + 1 
Wend 

exl.Visible = True 
Set exl = Nothing 
Set shl = Nothing 
Set fso = Nothing 
Set exe = Nothing 
WScript.Quit 

Function getIP(text) 
    Dim s 

    s = Mid(text, Len("Ping statistics for ") + 1) 
    getIP = Trim(Replace(s,":","")) 
End Function 

然而,exec函數沒有WindowStyle選項,所以你會看到命令處理器閃存彌補每次運行ping時間。

+0

「它沒有'執行'功能,可以讓你連接進程的'標準輸出'。 WshShell.Exec(...).StdOut'怎麼樣? [實施例](http://msdn.microsoft.com/en-us/library/cbxxzwb5(V = vs.84)的.aspx)。 – Helen

+0

我沒有意識到這個對象的存在。缺點是要獲得StdOut屬性,你必須使用'Exec',它沒有選項可以在後臺運行。我會編輯這個答案,因爲它仍然是一個更好的方法來做到這一點 – Jobbo

0

您可以改爲使用腳本shell的RUN方法,並將ping語句輸出到文本文件。然後在ping語句完成後讀取文本文件並獲取信息。

Set objWSH = CreateObject("WScript.Shell") 
objWSH.Run "%COMSPEC% /c ping -n 1 """ & host & """ | Find ""statistics for"" > temp.txt", 0, True 
Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objFile = objFSO.OpenTextFile("temp.txt", 1) 
out = Trim(objFile.ReadAll) 
If out <> "" Then 
    ' Read ping data 
Else 
    ' Ping failed to run 
End If 

或沿着這些線。這應該讓你走上正軌。