Search code examples
vbscriptwmiwmic

Join value of the properties in the For Each loop to one line output


Sorry for my bad English.

At here Parse properties string in an array to For Each loop, with support from https://stackoverflow.com/users/1630171/ I was able to read the battery information. But it is just separate information, so how do we assemble it and export the results into one line.

Dim strResult, objItem, arrayItem
On Error Resume Next
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery")
arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")
For Each objItem in colItems
     For Each arrayItem In arrayItems
        strResult = Join(objItem.Properties_(arrayItem))
    Next
    WScript.Echo strResult
Next

And it shows empty result of the output.


Solution

  • You need to collect the properties and join them into a string.

    Try this:

    Option Explicit
    
    Dim objItem, arrayItems, strComputer
    Dim objWMIService, colItems, arrResult, i
    
    strComputer = "."
    Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
    
    'The third parameter 48 for 'ExecQuery' is the combination of wbemFlagForwardOnly + wbemFlagReturnImmediately
    'see: https://learn.microsoft.com/en-us/windows/desktop/wmisdk/swbemservices-execquery#parameters
    Set colItems = objWMIService.ExecQuery("Select * from Win32_Battery",,48)
    arrayItems = Array("Name", "Availability", "BatteryStatus", "Chemistry")
    
    For Each objItem in colItems
        'create/clear an array to store the various pieces of information
        ReDim arrResult(UBound(arrayItems))
        For i = 0 To (UBound(arrayItems))
            ' Sometimes the WMI property returns a Null value (Nothing)..
            If Not IsNull (objItem.Properties_(arrayItems(i))) Then
                arrResult(i) = objItem.Properties_(arrayItems(i))
            Else
                arrResult(i) = "Unknown"
            End If
        Next
        'as example I'm using the Tab character to join the pieces
        WScript.Echo Join(arrResult, Chr(9))
    Next