JScript枚举器和属性列表 [英] JScript Enumerator and list of properties

查看:84
本文介绍了JScript枚举器和属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下WSH代码段:

Consider the following WSH snippet:


var query = GetObject("winmgmts:").ExecQuery("SELECT Name FROM Win32_Printer", "WQL", 0);
var e = new Enumerator(query);
for ( ; !e.atEnd(); e.moveNext ()) { 
    var p = e.item();
    WScript.Echo(p.Name + " (" + p.Status + ")");
}

它将在每行中打印一个打印机名称,并在方括号中打印单词"undefined"(因为p对象中不存在Status属性).问题是:如何列出p中的所有可用属性? for (var i in p) {...}的常规技术不起作用-似乎p对象中的属性不可枚举.

It prints in every line a printer name and the word "undefined" in brackets (because Status property isn't exist in p object). The question is: how can I list all available properties from p? The usual technique with for (var i in p) {...} doesn't work--it seems that properties in p object aren't enumerable.

谢谢.

推荐答案

JScript的for...in语句与WMI对象不兼容,因为它们比本机JScript对象更复杂. WMI对象通过特殊的 Properties_ 公开其属性集合a>属性,因此要列出对象的所有可用属性,您需要枚举此集合,就像枚举查询结果以访问单个WMI对象一样.每个对象属性均由 SWbemProperty 表示具有NameValue和其他属性的对象,提供有关适当对象属性的信息.

JScript's for...in statement isn't compatible with WMI objects, because, well, they are more complex than native JScript objects. WMI objects expose their property collection via the special Properties_ property, so to list all available properties of an object, you need to enumerate this collection like you enumerate the query results to access individual WMI objects. Each object property is represented by a SWbemProperty object that has the Name, Value and other properties providing info about the appropriate object property.

此示例应帮助您理解:

var query = GetObject("winmgmts:").ExecQuery("SELECT Name, Status FROM Win32_Printer");
var colPrinters = new Enumerator(query);

var oPrinter, colProps, p;

// Enumerate WMI objects
for ( ; !colPrinters.atEnd(); colPrinters.moveNext()) { 
    oPrinter = colPrinters.item();

    // Enumerate WMI object properties
    colProps = new Enumerator(oPrinter.Properties_);
    for ( ; !colProps.atEnd(); colProps.moveNext()) { 
        p = colProps.item();
        WScript.Echo(p.Name + ": " + p.Value);
    }
}

请注意,此脚本还将显示DeviceID属性值,因为它是Win32_Printer类的键属性,因此也将对其进行检索以唯一地标识类实例.

Note that this script will also display the DeviceID property value, because it's a key property of the Win32_Printer class, so it's also retrieved in order to uniquely identify class instances.

这篇关于JScript枚举器和属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆