Search code examples
vbscriptwsh

Why is my VBScript throwing nine Pop Ups instead of one?


I have a Win7 64 bit Windows Professional Laptop. I have a VB Script taken from the net and with certain alterations I am trying to get at Link speed for all Adaptors on my Laptop. The Vb script seems to be working except that I have to enter 9 times to get a complete list of all instances. This means that when I double click the script, the pop up shows only one instance. When I press Enter again, it shows the first and the second one, and likewise till I press Enter, nine times, I get the complete list, in one Pop Up. I know this is possible on the command prompt using CScript, but I prefer to get a single Popup. I am not very versatile on VBScripts but I am willing to learn. Am I missing something ? Any help will be appreciated. Here's my script.

strComputer = "."
strRslt = Wscript.ScriptName _
    & vbTab & "Computer Information " & vbcr _ 
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\WMI")
Set colItems = objWMIService.ExecQuery("SELECT * FROM MSNdis_LinkSpeed" ,,48)  
For Each objItem in colItems
strRslt = strRslt & vbNewLine  _
& "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
& "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps" 
msgbox strRslt,&h51000, "speed"
Next

Solution

  • The issue is a simple one that many can make when first starting out with VBScript or other similar languages.

    The For Each statement will iterate through a list of objects until it reaches the end of the list, in this case nine object instances. The command is structured in such a way that any commands within the For and Next block will be executed for the current instance that is identified by the variable after Each. As the MsgBox() function is running inside the For it will be displayed for each object instance.

    If you didn’t expect this the simple fix is to move the MsgBox() outside of the loop.

    For Each objItem in colItems
        strRslt = strRslt & vbNewLine  _
        & "InstanceName: " & vbTab & objItem.InstanceName & vbcr _
        & "NdisLinkSpeed: " & vbTab & objItem.NdisLinkSpeed/10 & " kbps"
    Next
    msgbox strRslt,&h51000, "speed"