The variable for the loop keeps the old cost

I have a program that reads hostnames from a txt file, scans the network for the hostname, and then displays the hostname and the corresponding Windows operating system (CAPTION).

I am trying to upgrade all Windows XP computers to Windows 7. I am trying to run this list to give me an idea of ​​how many machines I have upgraded and how much more I need to upgrade, etc.

The problem is that when I use the statement On Error Resume Next

, if the script tries to bind to the hostname which is BAD HOST, or if the hostname is DOWN, it displays the operating system from the last hostname. Then every name that does a scan is moved forward revealing that same operating system.

What could be causing this error?

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

      

+3


source to share


1 answer


Using Global On Error Resume Next

simply requires a desaster - all errors will be ignored, the assignment will not be performed as you expect, and the stale data will be used.

It:

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

      

output:



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

      

demonstrates strictly local error handling (the maximum allowed operation between OERN and OEG0) for your first risky task. You will have to protect / guard others accordingly, or check the return values.

(see this for a global error handling strategy)

+1


source







All Articles