【发布时间】:2015-06-18 04:25:50
【问题描述】:
场景:我正在使用 Select-Object 访问管道对象的属性,其中一个属性本身就是一个对象。我们称之为PropertyObject。我想访问该 PropertyObject 的一个属性,比如 Property1。是否有任何访问 Property1 的好方法和干净的方法,如下所示:
...| select-object PropertyObject.Property1
在进行实验时,只有执行以下操作才能使其正常工作:
...| select-object {$_.PropertyObject.Property1}
如果我想用一个像样的列名来显示它,它会变得更加混乱:
...| select-object @{Name="Property1"; Expression={$_.PropertyObject.Property1}}
鉴于 PowerShell 总体上是多么的简洁明了,我不禁想我遗漏了一些东西,应该有一种更简洁的方式来访问属性的属性。有吗?
编辑:按照马特的要求,这里是具体的例子:
我正在读取一个 XML 文件,Books3.xml:
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date inprint="false">2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
<publisher>
<name>Simon and Schuster</name>
<country>USA</country>
<city>New York</city>
</publisher>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date inprint="true">2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
<publisher>
<name>HarperCollins</name>
<country>USA</country>
<city>New York</city>
</publisher>
</book>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date inprint="false">2000-11-17</publish_date>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
<publisher>
<name>Macmillan</name>
<country>United Kingdom</country>
<city>London</city>
</publisher>
</book>
</catalog>
将 XML 加载到 XmlDocument 中的代码:
$filePath = "C:\Temp\books3.xml"
$xmlDoc = new-object xml
$xmlDoc.load($filePath)
尝试阅读每本书的详细信息:
$xmlDoc.catalog.book | select author, title, publisher.name
结果:
author title publisher.name
------ ----- --------------
Gambardella, Matthew XML Developer's Guide
Ralls, Kim Midnight Rain
Corets, Eva Maeve Ascendant
【问题讨论】:
-
你的 powershell 版本是什么?如果它是 3.0,您可以只使用
$object.PropertyObject.Property1,否则您只需链接选择select PropertyObject | select Property1。您可能需要在其中进行一些扩展,但这就是要点。这一切都取决于道具 -
我做了一个小更新,但我认为这不是您正在寻找的答案。提取单个属性比您要查找的对象输出更容易。
Select是解决这个问题的方法。您可以通过将哈希移动到单个变量来清理它,但它不会更改所需的代码。
标签: powershell pipeline powershell-4.0