Thursday, September 23, 2010

Comparing XML files with Select-XML and Compare-Object

My situation: 80+ automated powershell tests scripts that take 6 hours to run, all of which make changes to an XML config file, and don't always restore the config when the test is finished, causing other tests to fail.

My solution: I have a script that runs before any testing is done and after every test script that saves the config file to a directory, with a time stamp in the name. All I have to do now is compare the first XML, which I know to be good, with the rest. This is what I came up with:

# Get all the XML's that are saved and sort by CreationTime
$xmls = Get-ChildItem -Path "C:\RESULTS\logs\*config.xml" | Sort-Object -Property CreationTime

# Get the first out of the list and create an XML object
[xml]$first = Get-Content -Path $xmls[0].fullname

# Use the Select-XML and the specified xpath to get all the nodes under the \\Config node
# this can be changed howerever you want, depending on how your XML is set up
$base = Select-Xml -Xml $first -XPath "//Config/*"

# Get loopy
# Loop through the XML's, cast each as an XML object, then compare to the nodes of the first
$xmls | ForEach-Object {

[xml]$temp = Get-Content $_.fullname

Compare-Object -ReferenceObject $base -DifferenceObject (Select-Xml -Xml $temp -XPath "//Config/*")

}

Have fun and Get-Command!!

1 comment:

  1. Hi,

    Can you pls. provide me a sample script which can scan and compare two web.config files and produce an output that can display the list of differences found? It should specifically list Web Config1 and Web Config2 in the column header on the ouput, possible?

    Thanks!

    ReplyDelete