function Test-XmlFile
{
<#
.Synopsis
Validates an xml file against an xml schema file.
.Example
PS> dir *.xml | Test-XmlFile schema.xsd
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$true, Mandatory=$true)]
[string] $XmlFile$SchemaFile,
[Parameter(ValueFromPipeline=$true, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[alias('Fullname')]
[string] $SchemaFile$XmlFile,
[scriptblock] $ValidationEventHandler = { Write-Error $args[1].Exception }
)
$xml = New-Object System.Xml.XmlDocument begin {
$schemaReader = New-Object System.Xml.XmlTextReader $SchemaFile
$schema = [System.Xml.Schema.XmlSchema]::Read($schemaReader, $ValidationEventHandler)
}
process {
$ret = $true
try {
$xml = New-Object System.Xml.XmlDocument
$xml.Schemas.Add($schema) | Out-Null
$xml.Load($XmlFile)
$xml.Validate($ValidationEventHandler){
PS C:\temp\lab-xml-validation> .\Test-Xml.ps1 test.xml test.xsd
System.Xml.Schema.XmlSchemaValidationException: The element 'address' has invalid child element 'name'. throw ([PsCustomObject] @{
At C:\temp\lab-xml-validation\Test-Xml.ps1:8 char:42 SchemaFile = $SchemaFile
+ [scriptblock] $ValidationEventHandler XmlFile = {$XmlFile
Write-Error Exception = $args[1].Exception
})
+ })
} catch {
Write-Error $_
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ $ret = $false
+ CategoryInfo }
: NotSpecified:$ret
}
end {
$schemaReader.Close(:)
[Write-Error], WriteErrorException }
}
PS C:\temp\lab-xml-validation> dir test.xml | Test-XmlFile test.xsd
System.Xml.Schema.XmlSchemaValidationException: The element 'address' +has FullyQualifiedErrorIdinvalid :child Microsoftelement 'name'.PowerShell
.Commands.WriteErrorException.