PowerShell/scripts/check-xml-file.ps1

44 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
2023-12-06 10:12:33 +01:00
Verifies the given 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
2021-10-16 16:50:10 +02:00
Specifies the path to the XML file to check
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++ })
$Reader = [System.Xml.XmlReader]::Create($XmlFile.FullName, $ReaderSettings)
while ($Reader.Read()) { }
$Reader.Close()
if ($script:ErrorCount -gt 0) {
2023-12-06 10:12:33 +01:00
throw "Invalid XML in '$path'"
2021-02-10 20:37:37 +01:00
}
2021-08-24 20:46:03 +02:00
2023-12-06 10:12:33 +01:00
"✔️ Valid XML in '$path'"
2021-09-27 10:09:45 +02:00
exit 0 # success
} catch {
2022-04-13 12:06:32 +02:00
"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
exit 1
}