What exception type should be used in Powershell to catch a XML parse error due to invalid characters?
exception, powershell, powershell-2.0, xml-parsing
Solution
Here is a way to discover yourself the full type name of an Exception, the result here gives System.Management.Automation.ArgumentTransformationMetadataException as given by @Adrian Wright.
Clear-Host
try {
[xml]$xml = Get-Content "c:\Temp\1.cs" # line 2
}
catch {
# Discovering the full type name of an exception
Write-Host $_.Exception.gettype().fullName
Write-Host $_.Exception.message
}
Problem
Line 2 in the script below generates - "Cannot convert value "System.Object[]" to type "System.Xml.XmlDocument". Error: "'→', hexadecimal value 0x1A, is an invalid character. Line 39, position 23." At line:1 char:8 + [xml]$x <<<< = Get-Content 4517.xml + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException" What exception should be specified on line 4 (of the script) to catch the aforementioned error? ``` try { [xml]$xml = Get-Content $file # line 2 } catch [?] { # line 4 echo "XML parse error!" # handle the parse error differently } catch { echo $error # some general error } ``` Thanks for looking (and answering) Adrian