Reputation: 5
I am trying to parse XML files in a directory where a keyword is defined. If the keyword is found, it should first be replaced to avoid further matching and then the contents of the xml will be sent as the message portion of an event.
The main issue is with the last code block, where it parses the .xml line by line instead of as a block.
#### 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" + ($_))
}
}
But I cannot seem to make the code do the following: Read the file, if it contains "Major" Parse the whole .xml as a "Write EventLog -Message" and once it is parsed, change the keyword Major to the word Parsed.
Upvotes: 0
Views: 777
Reputation: 1884
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)
}
Upvotes: 1
Reputation: 201622
Another route to go is:
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
}
}
In PowerShell v2 you don't have the -Raw parameter on Get-Content to read the file as a single string. You can use [IO.File]::ReadAllText() instead.
Upvotes: 0