7

How would I find a multiline pattern in files, such as the contents of an XML node, using Powershell?

i.e. if I were looking for the word "green" within the deviceDescription node, but the XML node text may span multiple lines, this doesn't work:

dir -r -i *.xml | select-string -Pattern "<deviceDescription>.*green.*</deviceDescription>"

1 Answer 1

10

First of all, if is xml, extract the device description string treating it as such and then match for the string you want, in this case, green.

$x = [xml] (gc .\test.xml)
$x.deviceDescription -match "green"

If you don't want to go that way, you will have to use the ?s - singleline or dotall flag which makes * match newlines:

$x = [IO.File]::ReadAllText("C:\test.xml")
$x -match "(?s)<deviceDescription>.*green.*</deviceDescription>"

Note that you probably want to use .*? or this may span across multiple deviceDescription tags. Edge cases like this are reasons why you should avoid using regex for such things.

Sign up to request clarification or add additional context in comments.

1 Comment

How can I output the text of the node? I have this: $x.SelectNodes("//deviceDescription") | select-object Node

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.