What exception type should be used in Powershell to catch a XML parse error due to invalid characters?

て烟熏妆下的殇ゞ 提交于 2019-12-01 16:41:27

问题


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


回答1:


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
}



回答2:


System.Management.Automation.ArgumentTransformationMetadataException



来源:https://stackoverflow.com/questions/10392807/what-exception-type-should-be-used-in-powershell-to-catch-a-xml-parse-error-due

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!