Search code examples
xmlparsingpowershellcustom-eventlog

Powershell XML Parsing and writing to the event viewer


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.


Solution

  • 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)
    }