0

我正在尝试在定义了关键字的目录中解析 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 一词。

4

2 回答 2

1

Your code reads line by line because you asked for it:

   (Get-Content $_)| ForEach { ...  }

will loop through each line of the file $_.

So I suppose you would prefer:

Get-ChildItem C:\test\*.xml | ForEach {
Write-EventLog –LogName Application –Source “Verint Alert” `
    –EntryType Information –EventID 1 `
    -Message ("Triggered Alarm" + (Get-Content $_))
}

BTW, you also need to filter the files you are working on.

Edit about filtering:

Stated you have something like <status>Major</status> in your file

$xmlfile=$_
$xml=[xml] (gc $xmlfile)
if ( $xml.SelectSingleNode("//status").'#text' -eq "Major") { 
    # Write-EventLog...
    $xml.SelectSingleNode("//status").'#text' = 'Parsed'
    $xml.Save($xmlfile)
}
于 2015-04-19T00:24:19.817 回答
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()。

于 2015-04-19T01:00:27.103 回答