PowerShell/scripts/check-xml-file.ps1

43 lines
1.2 KiB
PowerShell
Raw Normal View History

2023-10-31 12:12:58 +01:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
Verifies an XML file
2021-10-04 21:29:23 +02:00
.DESCRIPTION
2022-01-29 12:47:46 +01:00
This PowerShell script checks the given XML file for validity.
2023-12-06 10:12:33 +01:00
.PARAMETER path
Specifies the path to the XML file
2021-07-13 21:10:02 +02:00
.EXAMPLE
2023-12-06 10:12:33 +01:00
PS> ./check-xml-file.ps1 myfile.xml
Valid XML in 📄myfile.xml
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-29 12:47:46 +01:00
.NOTES
2022-09-06 21:42:04 +02:00
Author: Markus Fleschutz | License: CC0
2020-12-29 15:14:21 +01:00
#>
2023-12-06 10:12:33 +01:00
param([string]$path = "")
2021-02-18 20:17:55 +01:00
try {
2023-12-06 10:12:33 +01:00
if ($path -eq "" ) { $path = Read-Host "Enter path to XML file" }
2021-07-15 15:51:22 +02:00
2023-12-06 10:12:33 +01:00
$XmlFile = Get-Item $path
# Perform the XSD Validation
2023-12-06 10:12:33 +01:00
$script:ErrorCount = 0
$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++ })
$ReaderSettings.DtdProcessing = [System.Xml.DtdProcessing]::Parse
$Reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $ReaderSettings)
while ($Reader.Read()) { }
$Reader.Close()
if ($script:ErrorCount -gt 0) { throw "Invalid XML" }
2021-08-24 20:46:03 +02:00
"✔️ Valid XML in 📄$path"
2021-09-27 10:09:45 +02:00
exit 0 # success
} catch {
"⚠️ $($Error[0]) in 📄$path"
exit 1
}