PowerShell/Scripts/check-xml-file.ps1

46 lines
1.3 KiB
PowerShell
Raw Normal View History

2021-09-27 10:38:12 +02:00
<#
2021-07-13 21:10:02 +02:00
.SYNOPSIS
2021-09-24 17:19:49 +02:00
Checks the given XML file for validity
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.
2021-10-16 16:50:10 +02:00
.PARAMETER file
Specifies the path to the XML file to check
2021-07-13 21:10:02 +02:00
.EXAMPLE
2021-09-24 17:19:49 +02:00
PS> ./check-xml-file myfile.xml
2021-10-04 17:42:06 +02:00
XML file is valid
2021-07-13 21:10:02 +02:00
.LINK
https://github.com/fleschutz/PowerShell
2022-01-29 12:47:46 +01:00
.NOTES
Author: Markus Fleschutz / License: CC0
2020-12-29 15:14:21 +01:00
#>
2021-09-24 17:19:49 +02:00
param([string]$file = "")
2021-02-18 20:17:55 +01:00
try {
2021-09-24 17:19:49 +02:00
if ($file -eq "" ) { $file = read-host "Enter path to XML file" }
2021-07-15 15:51:22 +02:00
2021-09-24 17:19:49 +02: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-09-27 10:09:45 +02:00
exit 0 # success
} catch {
2021-09-16 20:19:10 +02:00
"⚠️ Error: $($Error[0]) ($($MyInvocation.MyCommand.Name):$($_.InvocationInfo.ScriptLineNumber))"
exit 1
}