在Powershell中应该使用什么异常类型来捕获由于无效字符而导致的XML解析错误?

Adr*_*ght 6 powershell exception-handling powershell-2.0 xml-parsing

下面脚本中的第2行生成 -

"无法转换值"System.Object []"键入"System.Xml.XmlDocument".错误:"'→',十六进制值0x1A,是无效字符.第39行,第23位."

在行:1 char:8 + [xml] $ x <<<< = Get-Content 4517.xml + CategoryInfo:MetadataError:(:) [],ArgumentTransformationMetadataException + FullyQualifiedErrorId:RuntimeException"

应该在第4行(脚本)指定什么异常来捕获上述错误?

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
}
Run Code Online (Sandbox Code Playgroud)

感谢您寻找(并回答)

阿德里安

JPB*_*anc 5

这是一种发现自己的Exception的完整类型名称的方法,这里的结果给出了@Adrian Wright给出的System.Management.Automation.ArgumentTransformationMetadataException.

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
}
Run Code Online (Sandbox Code Playgroud)