我正在尝试解析定义关键字的目录中的XML文件。 如果找到关键字,则应首先替换它以避免进一步匹配,然后将xml的内容作为事件的消息部分发送。
主要问题是最后一个代码块,它逐行解析.xml而不是块。
#### THIS CODE GETS ALL THE FILES THAT CONTAINS THE "Major" Pattern
$Path = "C:\test\"
$SearchFor = "Major"
$TestFor = "parsedxml"
$Parse = "ParsedXML"
$PathArray = @()
$FolderFile = "C:\test\*.xml"
$found = @()
# This code snippet gets all the files in $Path that end in ".xml".
Get-ChildItem $Path -Filter "*.xml" | Select-String -Pattern "Major"
ForEach-Object {
If (Get-Content $FolderFile | Select-String -Pattern
"Major","Parsedxml")
{
}
}
#### THIS WORKS TO CHANGE THE KEYWORD IN THE FILE ###
Get-ChildItem C:\test\*.xml -recurse | ForEach {
(Get-Content $_ | ForEach {$_ -replace "Major", "Parsed"}) | Set-Content $_
}
### THIS WORKS (KINDA) TO PARSE THE FILE INTO AN EVENTLOG ###
### BUT IT PARSES THE .XML LINE BY LINE FOR SOME REASON ####
Get-ChildItem C:\test\*.xml | ForEach {
(Get-Content $_)| ForEach { Write-EventLog –LogName Application –Source “Verint Alert” –EntryType Information –EventID 1 -Message ("Triggered Alarm" + ($_))
}
}
但我似乎无法使代码执行以下操作: 阅读文件,如果它包含" Major"将整个.xml解析为" Write EventLog -Message"一旦解析,将关键字Major更改为单词Parsed。
答案 0 :(得分:1)
您的代码会逐行读取,因为您要求它:
(Get-Content $_)| ForEach { ... }
将循环遍历文件$ _。
的每一行所以我想你更喜欢:
Get-ChildItem C:\test\*.xml | ForEach {
Write-EventLog –LogName Application –Source “Verint Alert” `
–EntryType Information –EventID 1 `
-Message ("Triggered Alarm" + (Get-Content $_))
}
顺便说一句,你还需要过滤你正在处理的文件。
编辑过滤:
说明您的文件中有<status>Major</status>
$xmlfile=$_
$xml=[xml] (gc $xmlfile)
if ( $xml.SelectSingleNode("//status").'#text' -eq "Major") {
# Write-EventLog...
$xml.SelectSingleNode("//status").'#text' = 'Parsed'
$xml.Save($xmlfile)
}
答案 1 :(得分:0)
另一条路线是:
foreach ($file in (Get-ChildItem c:\test\*.xml)) {
$content = [IO.File]::ReadAllText($file.FullName)
if ($content -match 'Major') {
Write-Event -LogName Application -Source 'Verint Alert' `
-EntryType Information -EventId 1 `
-Message "Triggered Alarm $content";
$content -replace 'Major','Parsed' | Out-File $file.FullName
}
}
在PowerShell v2中,您没有在Get-Content上使用-Raw参数将文件作为单个字符串读取。您可以使用[IO.File] :: ReadAllText()代替。