获取 WMI 对象并列出其某些属性

此示例将列出所有连接的监视器的首选分辨率。

代码:

On Error Resume Next
strComputer = "."
strQuery = "SELECT PreferredMonitorSourceModeIndex, MonitorSourceModes " & _
           "FROM WmiMonitorListedSupportedSourceModes"

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\ROOT\WMI")
Set colItems = objWMIService.ExecQuery(strQuery, , 48)

For Each objItem In colItems
  i = objItem.PreferredMonitorSourceModeIndex
  wscript.stdout.writeline "InstanceName: " & objItem.instancename
  wscript.stdout.writeline "Horizontal: " & objItem.MonitorSourceModes(i).HorizontalActivePixels
  wscript.stdout.writeline "Vertical: " & objItem.MonitorSourceModes(i).VerticalActivePixels
Next

我们首先获得 WMI 服务。它不可创造。

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\ROOT\WMI")

接下来,使用 WQL 设置我们的查询。WQL 与 SQL 非常相似。

strQuery = "SELECT PreferredMonitorSourceModeIndex, MonitorSourceModes " & _
           "FROM WmiMonitorListedSupportedSourceModes"

WMI 类 WmiMonitorListedSupportedSourceModes 有 5 个属性:InstanceName,Active,MonitorSourceModes,NumOfMonitorSourceModes 和 PreferredMonitorSourceModeIndex。MonitorSourceModes 是一个数组,我们必须查询 PreferredMonitorSourceModeIndex 以确定数组的哪个元素包含我们寻找的信息。

现在让我们执行查询

Set colItems = objWMIService.ExecQuery(strQuery, , 48)

并循环结果:

For Each objItem In colItems
  i = objItem.PreferredMonitorSourceModeIndex
  wscript.stdout.writeline "InstanceName: " & objItem.instancename
  wscript.stdout.writeline "Horizontal: " & objItem.MonitorSourceModes(i).HorizontalActivePixels
  wscript.stdout.writeline "Vertical: " & objItem.MonitorSourceModes(i).VerticalActivePixels
Next