獲取 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