PowerShell/Scripts/check-xml-file.ps1

38 lines
1.1 KiB
PowerShell
Raw Normal View History

2020-12-29 15:14:21 +01:00
<#
2021-04-07 15:17:49 +02:00
.SYNTAX check-xml-file [<file>]
2021-03-22 20:10:18 +01:00
.DESCRIPTION checks the given XML file for validity
.LINK https://github.com/fleschutz/PowerShell
.NOTES Author: Markus Fleschutz / License: CC0
2020-12-29 15:14:21 +01:00
#>
2021-02-10 20:37:37 +01:00
param($File = "")
2021-02-18 20:17:55 +01:00
if ($File -eq "" ) {
$File = read-host "Enter path to XML file"
}
try {
2021-02-10 20:37:37 +01:00
$XmlFile = Get-Item $File
$script:ErrorCount = 0
# Perform the XSD Validation
$ReaderSettings = New-Object -TypeName System.Xml.XmlReaderSettings
$ReaderSettings.ValidationType = [System.Xml.ValidationType]::Schema
$ReaderSettings.ValidationFlags = [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessInlineSchema -bor [System.Xml.Schema.XmlSchemaValidationFlags]::ProcessSchemaLocation
$ReaderSettings.add_ValidationEventHandler({ $script:ErrorCount++ })
$Reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $ReaderSettings)
while ($Reader.Read()) { }
$Reader.Close()
if ($script:ErrorCount -gt 0) {
2021-02-10 20:37:37 +01:00
write-warning "Invalid XML file"
exit 1
2021-02-10 20:37:37 +01:00
}
write-host -foregroundColor green "OK - XML file is valid"
exit 0
} catch {
2021-05-02 21:30:48 +02:00
write-error "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}