How do I use PowerShell to Validate XML files against an XSD?

前端 未结 8 1915
小鲜肉
小鲜肉 2020-12-05 02:26

As a part of my development I\'d like to be able to validate an entire folder\'s worth of XML files against a single XSD file. A PowerShell function seems like a good candid

8条回答
  •  感动是毒
    2020-12-05 03:06

    the solution of (Flatliner DOA) is working good on PSv2, but not on Server 2012 PSv3.

    the solution of (wangzq) is working on PS2 and PS3!!

    anyone who needs an xml validation on PS3, can use this (based on wangzq's function)

    function Test-Xml {
        param (
        [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
            [string] $XmlFile,
    
            [Parameter(Mandatory=$true)]
            [string] $SchemaFile
        )
    
        [string[]]$Script:XmlValidationErrorLog = @()
        [scriptblock] $ValidationEventHandler = {
            $Script:XmlValidationErrorLog += $args[1].Exception.Message
        }
    
        $xml = New-Object System.Xml.XmlDocument
        $schemaReader = New-Object System.Xml.XmlTextReader $SchemaFile
        $schema = [System.Xml.Schema.XmlSchema]::Read($schemaReader, $ValidationEventHandler)
        $xml.Schemas.Add($schema) | Out-Null
        $xml.Load($XmlFile)
        $xml.Validate($ValidationEventHandler)
    
        if ($Script:XmlValidationErrorLog) {
            Write-Warning "$($Script:XmlValidationErrorLog.Count) errors found"
            Write-Error "$Script:XmlValidationErrorLog"
        }
        else {
            Write-Host "The script is valid"
        }
    }
    
    Test-Xml -XmlFile $XmlFile -SchemaFile $SchemaFile
    

提交回复
热议问题