[我是PowerShell的初学者]
我想使用PowerShell从特定目录下的所有文件中提取特定模式。我该怎么做?
例如,让文件内容为:
<node1>Hello World ignore</node1>
<wantedNode>Hello World extract
this text </wantedNode>
我想只提取包含“hello world”(不区分大小写)的类型的节点:
"Hello World extract this text"
答案 0 :(得分:2)
如果文件是正确的XML文档,那么这很容易,例如:
Get-ChildItem *.xml | Select-Xml '//wantedNode' | Format-List Path, @{n="Text";e={$_.Node.InnerText}}
如果XML文档具有默认名称空间,则会变得有点棘手,但不会太多。如果您需要进行正则表达式搜索,那么因为感兴趣的文本跨越多行,您需要将文件作为单个字符串读取,例如:
[IO.File]::ReadAllText("$pwd\test.xml") |
Select-String '(?s)(?<=\<wantedNode\>)(.*?)(?=\</wantedNode\>)' |
Format-List Matches
在PowerShell v3中,这有点简单:
Get-Content .\test.xml -Raw |
Select-String '(?s)(?<=\<wantedNode\>)(.*?)(?=\</wantedNode\>)' |
Format-List Matches
答案 1 :(得分:2)
试试这个,我添加了一个根节点:
[xml]$xml=@"
<root>
<node1>Hello World ignore</node1>
<wantedNode>Hello World extract this text</wantedNode>
</root>
"@
$xml.SelectNodes("//wantedNode[contains(.,'Hello World')]") | foreach {$_.'#text'}
答案 2 :(得分:1)
谷歌搜索了一段时间后,我想出了一个解决方案:
$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
}
}
}