1

[I am a beginner with PowerShell]

I want to use PowerShell to extract a specific pattern from all files under a certain directory. How do I do that?

For example, let the file content be:

<node1>Hello World ignore</node1> 
<wantedNode>Hello World extract
this text </wantedNode>

I want to extract only nodes of type that contain "hello world" (case insensitive):

"Hello World extract this text"
2
  • 1
    why should node1 be ignored? Both nodes contain "hello world"... Commented May 2, 2012 at 16:28
  • That is my requirement - I want to get all nodes of type wantedNode that contain Hello World Commented May 2, 2012 at 17:14

3 Answers 3

2

If the file is a proper XML document then this is pretty easy e.g.:

Get-ChildItem *.xml | Select-Xml '//wantedNode' | Format-List Path, @{n="Text";e={$_.Node.InnerText}}

If the XML docs have default namespaces this gets a bit trickier but not much. If you need to do regex search then because the text of interest spans multiple lines you need to read the files in as a single string e.g.:

[IO.File]::ReadAllText("$pwd\test.xml") | 
    Select-String '(?s)(?<=\<wantedNode\>)(.*?)(?=\</wantedNode\>)' | 
    Format-List Matches

In PowerShell v3 this gets a bit simpler:

Get-Content .\test.xml -Raw | 
    Select-String '(?s)(?<=\<wantedNode\>)(.*?)(?=\</wantedNode\>)' | 
    Format-List Matches
Sign up to request clarification or add additional context in comments.

Comments

2

Try this, I added a root node:

[xml]$xml=@"
<root>
<node1>Hello World ignore</node1> 
<wantedNode>Hello World extract this text</wantedNode>
</root>
"@

$xml.SelectNodes("//wantedNode[contains(.,'Hello World')]") | foreach {$_.'#text'}

Comments

1

After googling for a while, I came up with a solution:

$files = gci -Recurse
foreach ($file in $files)
{
    $x = [xml] (Get-Content $file.FullName)
    foreach ($node in $x.SelectNodes("//wantedNode")) 
    {       
        if ($node.InnerText -like "*Hello World*" ) 
            { 
                Write-Host $node.InnerText
            } 
    }
}

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.