Scripting. Powershell, VMware, Windows, Active Directory & Exchange. All that kind of stuff…..
RSS icon Email icon Home icon
  • Quick and Easy PowerShell Test-XMLFile

    Posted on May 25th, 2012 Jonathan Medd No comments

    The PowerShell community extensions module contains Test-XML which can perform a number of checks for the validity of an XML file. For my particular needs I wasn’t able to take a dependency on an external module, consequently I needed to make something similar of my own to carry out some basic tests.

    The below function makes use of the XmlException exception from the XmlDocument class . An attempt is made to load the XML file and then any Load or Parse errors are caught by the XmlException exception.

    Let’s take a look at a couple of examples:

    The following XML file is missing a closing ‘/’ in Set 1 for Orange

    
    <Data>
    <Set1>
    <Name>Orange</Name>
    <Colour>Orange</Colour>
    <Set1>
    
    <Set1>
    <Name>Apple</Name>
    <Colour>Green</Colour>
    </Set1>
    </Data>
    
    

    The function will pick it up like this:

    
    Test-XMLFile Fruit.xml -verbose
    
    

    Note that it also returns $true or $false so you can use it say in ‘if’ statements.

    In this example an additional </Set1> has been erroneously copied into the wrong place.

    
    <Data>
    <Set1>
    <Name>Orange</Name>
    <Colour>Orange</Colour>
    </Set1>
    
    </Set1>
    <Set1>
    <Name>Apple</Name>
    <Colour>Green</Colour>
    </Set1>
    </Data>
    
    

    The function will pick it up like this:

    
    Test-XMLFile Fruit.xml -verbose
    
    

    
    function Test-XMLFile {
    <#
    .SYNOPSIS
    Test the validity of an XML file
    #>
    [CmdletBinding()]
    param (
    [parameter(mandatory=$true)][ValidateNotNullorEmpty()][string]$xmlFilePath
    )
    
    # Check the file exists
    if (!(Test-Path -Path $xmlFilePath)){
    throw "$xmlFilePath is not valid. Please provide a valid path to the .xml fileh"
    }
    # Check for Load or Parse errors when loading the XML file
    $xml = New-Object System.Xml.XmlDocument
    try {
    $xml.Load((Get-ChildItem -Path $xmlFilePath).FullName)
    return $true
    }
    catch [System.Xml.XmlException] {
    Write-Verbose "$xmlFilePath : $($_.toString())"
    return $false
    }
    }
    
    

     

    Leave a reply