场景:我正在使用Select-Object来访问管道对象的属性,其中一个属性本身是一个对象。我们称之为PropertyObject。我想访问该PropertyObject的一个属性,比如Property1。有没有一种简洁明了的方式来访问Property1,类似于:
...| select-object PropertyObject.Property1
在尝试实验的时候,我只能通过做类似以下的操作才能使其起作用:
...| select-object {$_.PropertyObject.Property1}
如果我想用一个合适的列名来显示它,那会变得更加混乱:
...| select-object @{Name="Property1"; Expression={$_.PropertyObject.Property1}}
鉴于PowerShell通常非常干净简洁,我不禁想到我可能错过了某些内容,也许有更清晰的方法可以访问属性中的属性。有吗?
编辑: 根据Matt的要求,这里是具体的示例:
我正在阅读一个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
$object.PropertyObject.Property1
。否则,你需要使用选择器链select PropertyObject | select Property1
。你可能需要在其中添加一些扩展,但这就是要点。这都取决于属性。 - MattSelect
是解决这个问题的方法。你可以通过将哈希移动到单个变量来简化它,但这并不改变所需的代码。 - Matt