使用Where-Object

时间:2019-11-29 13:35:17

标签: powershell

我有一个XML文件,其中包含有关包含程序包的序列的数据。 我正在尝试获取一个Powershell对象,其中包含有关失败软件包的信息。 (<PackageSuccess>False</PackageSuccess>

在下面找到包含样本数据的XML文件的结构。 (简体。我希望它还是真实的...)
您还可以找到用于过滤失败软件包的代码:

[xml]$Xml = @"
<?xml version="1.0" encoding="utf-8"?>
<Sequences>
  <Sequence>
    <SequenceName>Sequence1</SequenceName>
    <SequencePackages>
      <Package>
        <PackageName>Package1</PackageName>
        <PackageMeta>
          <PackageSuccess>True</PackageSuccess>
        </PackageMeta>
      </Package>
      <Package>
        <PackageName>Package2</PackageName>
        <PackageMeta>
          <PackageSuccess>False</PackageSuccess>
        </PackageMeta>
      </Package>
    </SequencePackages>
    <SequenceMeta>
      <Finished>True</Finished>
    </SequenceMeta>
  </Sequence>
  <Sequence>
    <SequenceName>Sequence2</SequenceName>
    <SequencePackages>
      <Package>
        <PackageName>Package3</PackageName>
      </Package>
    </SequencePackages>
  </Sequence>
</Sequences>
"@

Clear-Host

$ProcessedSequences = $Xml.Sequences.Sequence | Where-Object { $_.SequenceMeta.Finished -eq $true }
$FailedPackages = $ProcessedSequences.SequencePackages.Package | Where-Object { $_.PackageMeta.PackageSuccess -ne "True" }
$FailedPackages

输出如下:

PackageName PackageMeta
----------- -----------
Package2    PackageMeta

这可以确定,但是我也想在输出中使用SequenceName:

PackageName PackageSuccess SequenceName
----------- -----------    -----------
Package2    False          Sequence1

我无法为此找到干净的解决方案。

谢谢

1 个答案:

答案 0 :(得分:0)

将计算所得的属性与Select-Object一起使用,并在元素上使用ParentNode属性来向上移动到拥有SequenceName元素的祖先节点:

$FailedPackages |Select-Object PackageName,PackageMeta,@{Name='SequenceName';Expression={$_.ParentNode.ParentNode.SequenceName}}