Using Powershell to Search for Multiline Patterns in Files

How to find multiline pattern in files, for example, XML node content using Powershell?

i.e. if I were looking for the word "green" in a deviceDescriptionnode, but the XML node text can span multiple lines, this does not work:

dir -r -i *.xml | select-string -Pattern "<deviceDescription>.*green.*</deviceDescription>"
+5
source share
1 answer

First of all, if xml, extract the device description line, considering it as such, and then match the desired line, in this case green.

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

If you do not want to go this route, you will need to use a flag ?s- singleline or dotall, which will * correspond to newline characters:

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

, , , .*?, . , , , .

+9

All Articles