Validating Xml files using Powershell

Here is the thing, Visual Studio solution with 90+ projects, I'm ready to commit and push some changes to my Github repository. Then I see that I cannot push because somebody beat me and I'm forced to pull or rebase (I'm not going to discuss those terms here), yes you can feel it here it comes the "fear", when it comes to Git and merge conflicts I always find myself in this uncomfortable situation where I don't truly believe the Auto-Merge conflicts, specially when talking about two type of files:

  • .csproj
  • .config (app.config || web.config)

For some reason XML is one those things that even when Git believes that was smart enough to save us some headaches and solved the merge conflicts like a champ, some things can go wild.

So I created a little function in Powershell where I can use as:

  • a git hook
  • part of the build process
  • on demand

The code you can see it below

function Test-Xml {  
            Mandatory = $true, 
            ValueFromPipeline = $true,
            ValueFromPipelinebyPropertyName = $true)]
    Process {
        Write-Verbose "Testing file: $filePath"
        $xml = New-Object System.Xml.XmlDocument
        try {
            Write-Verbose "OK"
        catch [System.Xml.XmlException] {
            Write-Error "Not valid $filePath $($_.toString())"
            Write-Verbose "Error"


Get-ChildItem -Path mySolutionFolder\ -Recurse -Include app.config | Test-Xml  

The code above will search all the files called app.config inside mySolutionFolder and subdirectories. It will throw an error in case it finds a file that is not valid XML.

Note: In case you want to include web.config as well in the code above you can change it to *.config

Happy merges!