将 For Each 循环中的属性值连接到一行输出

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

抱歉我的英语不好。

这里, with support from https://whosebug.com/users/1630171/ 我能够读取电池信息。但它只是单独的信息,所以我们如何 assemble 它并将结果导出到一行。

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

并且它显示输出结果为空。

您需要收集属性并将它们连接成一个字符串。

试试这个:

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://docs.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