JScript 枚举器和属性列表
考虑以下 WSH 代码段:
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 + ")"); }
它在每一行中打印打印机名称和括号中的“未定义”一词(因为 Status
属性在 p
对象中不存在)。 问题是:如何列出 p
中的所有可用属性? for (var i in p) {...}
的常用技术不起作用 - 似乎 p
对象中的属性不可枚举。
提前致谢。
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 + ")"); }
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.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
JScript 的 for...in 语句与 WMI 对象不兼容,因为它们比本机 JScript 对象更复杂。 WMI 对象通过特殊的
Properties_< 公开其属性集合/code>
属性,因此要列出对象的所有可用属性,您需要枚举此集合,就像枚举查询结果以访问各个 WMI 对象一样。 每个对象属性均由
SWbemProperty
对象,具有Name
、Value
和其他属性,提供有关相应对象属性的信息。此示例应该可以帮助您了解这个想法:
请注意,此脚本还将显示
DeviceID
属性值,因为它是Win32_Printer
类的关键属性,因此也会在为了唯一地标识类实例。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 specialProperties_
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 aSWbemProperty
object that has theName
,Value
and other properties providing info about the appropriate object property.This example should help you get the idea:
Note that this script will also display the
DeviceID
property value, because it's a key property of theWin32_Printer
class, so it's also retrieved in order to uniquely identify class instances.如果您想避免每次需要迭代需要枚举器的集合对象时都需要使用显式枚举器,则可以定义一个小辅助函数,如下所示:
然后,对集合的迭代变得相当不那么笨拙:
If you'd like to avoid the need to use an explicit Enumerator every time you need to iterate over a collection object that needs one, you can define a little helper function like this:
Iteration over collections then becomes rather less clumsy:
我认为问题在于您的查询中您只询问名称。 尝试询问名称和状态:
我从 http://msdn.microsoft.com/en-us/library/aa394363(VS.85).aspx 和一些工作。 我查询了 DriverName 和 Comment,两者都有文本或至少为空。
I think the problem is in your query you're only asking for the Name. Try asking for both Name and status:
I got some more properties from http://msdn.microsoft.com/en-us/library/aa394363(VS.85).aspx and several work. I queried for DriverName and Comment and both had text or at least a null.