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

前端 未结 8 1904
小鲜肉
小鲜肉 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条回答
  •  萌比男神i
    2020-12-05 03:01

    I am using this simple snippet, always works and you don't need complicated functions. It this example I am loading configuration xml with data which are used later for deployment and server configuration:

    # You probably don't need this, it's just my way
    $script:Context = New-Object -TypeName System.Management.Automation.PSObject
    Add-Member -InputObject $Context -MemberType NoteProperty -Name Configuration -Value ""
    $ConfigurationPath = $(Join-Path -Path $PWD -ChildPath "Configuration")
    
    # Load xml and its schema
    $Context.Configuration = [xml](Get-Content -LiteralPath $(Join-Path -Path $ConfigurationPath -ChildPath "Configuration.xml"))
    $Context.Configuration.Schemas.Add($null, $(Join-Path -Path $ConfigurationPath -ChildPath "Configuration.xsd")) | Out-Null
    
    # Validate xml against schema
    $Context.Configuration.Validate(
        {
            Write-Host "ERROR: The Configuration-File Configuration.xml is not valid. $($_.Message)" -ForegroundColor Red
    
            exit 1
        })
    

提交回复
热议问题