2015-05-13 49 views
3

我有一個從txt文件中讀取主機名的程序,它掃描網絡中的主機名,然後顯示主機名及其各自的Windows操作系統(CAPTION)。For循環中的變量保留舊值

我想讓所有的Windows XP機器升級到Windows 7.我試圖運行這個列表來給我一個想法,我已升級了多少臺機器,以及我還有多少升級的想法,等

問題是,如果腳本試圖聯繫主機名是一個不良主機或者如果主機名是關閉的,則使用語句On Error Resume Next它會顯示最後一個主機名的操作系統。然後,每個正在掃描的名稱都顯示相同的操作系統。

什麼可能導致此錯誤?

On Error Resume Next 

const ForReading = 1 

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set objTextFile= objFSO.OpenTextFile _ 
    ("C:\users\bh\desktop\hostnames.txt", ForReading) 

strText = objTextFile.ReadAll 
objTextFile.close 

arrComputers = Split(strText, vbCrlf) 

for Each strComputer in arrComputers 
    Set objWMIService = GetObject("winmgmts:" _ 
     & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 

    Set colSettings = objWMIService.ExecQuery _ 
     ("Select * from Win32_OperatingSystem") 

    For Each objOperatingSystem in colSettings 
     Wscript.Echo strComputer & ": " & objOperatingSystem.Caption 
    Next 
Next 

回答

1

使用全球On Error Resume Next只是要求desaster - 所有的錯誤都將被忽略,分配將不會按照預期和stale data將用於完成。

此:

Dim aErr 

arrComputers = Split(". winxpsp3 nix") 

for Each strComputer in arrComputers 
    On Error Resume Next 
    Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2") 
    aErr = Array(Err.Number, Err.Description) 
    On Error Goto 0 
    If 0 = aErr(0) Then 
     Set colSettings = objWMIService.ExecQuery("Select * from Win32_OperatingSystem") 
     For Each objOperatingSystem in colSettings 
      Wscript.Echo strComputer & ": " & objOperatingSystem.Caption 
     Next 
    Else 
    WScript.Echo "can't reach", strComputer, "error:", Join(aErr) 
    End If 
Next 

輸出:

cscript 30223065.vbs 
.: Microsoft Windows XP Professional 
winxpsp3: Microsoft Windows XP Professional 
can't reach nix error: 462 The remote server machine does not exist or is unavailable 

演示了一個嚴格的地方的錯誤處理(最大OERN和OEG0之間的一個危險動作)你的第一個高風險的工作。您必須相應地保護/包裝其他人或檢查返回值。

(有關全局錯誤處理的策略,請參閱this