0

I have the following code in PowerShell:

[xml]$Xml = @"
<?xml version="1.0" encoding="utf-8"?>
<Sequences>
  <Sequence>
    <SequenceName>Sequence-A</SequenceName>
    <SequenceMeta>
      <SequenceStart>2019-07-23T17:26:54.710+02:00</SequenceStart>
      <SequenceEnd>2019-07-23T17:26:54.741+02:00</SequenceEnd>
    </SequenceMeta>
  </Sequence>
  <Sequence>
    <SequenceName>Sequence-B</SequenceName>
    <SequenceMeta>
      <SequenceStart></SequenceStart>
      <SequenceEnd></SequenceEnd>    
    </SequenceMeta>
  </Sequence>
</Sequences>
"@

Clear-Host
$Sequences = $Xml.Sequences.Sequence | Where-Object -Property SequenceMeta.SequenceEnd
$Sequences

Remove-Variable -Name Xml

As you see I load XML-Data and then I want to filter it with "Where-Object". I want to select those "Sequence(s)", where the property "SequenceEnd" has a value.

In this example, the result should be "Sequence-A". "Sequence-B" should not be shown in the results, because the "SequenceEnd"-property has no value.

I don't know how to select the sub-property "Sequence-End". I tried it like "SequenceMeta.SequenceEnd", but as you see this is not working.

I am looking for a one-liner. In reality the query will be much longer.

Thank you

1 Answer 1

0

You can use the following:

$Sequences = $xml.Sequences.Sequence | Where-Object {$_.SequenceMeta.SequenceEnd}
$Sequences

Since the contents within the Where-Object script block {} are a conditional expression specifically a comparison, a property with no value will yield $false and a property with a value will yield $true when no comparison operators are present. Where-Object returns all objects for which the script block statement is true.

There are some limitations with using your syntax for Where-Object, which is the comparison statement syntax. First, you can only reference the first level of properties available from the object you are piping. In other words, you can only compare SequenceMeta rather than SequenceMeta.SequenceEnd. The code $xml.Sequences.Sequence.SequenceMeta | Where-Object -Property SequenceEnd would return one object, but it would be at the SequenceMeta property level rather than its parent, which can be retrieved with the get_ParentNode method available to the XmlElement class. See below.

$Sequences = $xml.Sequences.Sequence.SequenceMeta | Where-Object -Property SequenceEnd
$Sequences.get_ParentNode()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.