PowerShell/Scripts/check-xml-file.ps1

44 lines
1.1 KiB
PowerShell
Raw Normal View History

2021-08-26 10:46:12 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
check-xml-file [<file>]
.DESCRIPTION
Checks the given XML file for validity
.EXAMPLE
PS> .\check-xml-file.ps1 myfile.xml
.LINK
https://github.com/fleschutz/PowerShell
.NOTES
2021-08-03 15:53:57 +02:00
Author: Markus Fleschutz
License: CC0
2020-12-29 15:14:21 +01:00
#>
2021-07-15 15:51:22 +02:00
param([string]$File = "")
2021-02-18 20:17:55 +01:00
try {
2021-07-15 15:51:22 +02:00
if ($File -eq "" ) { $File = read-host "Enter path to XML file" }
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
}
2021-08-24 20:46:03 +02:00
"✔️ XML file is valid"
2021-02-10 20:37:37 +01:00
exit 0
} catch {
2021-05-02 21:30:48 +02:00
write-error "⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}