<?xml version="1.0" encoding="utf-8"?>
<root><nodeNotClosed></root>
此PowerShell将捕获无效的强制转换异常:
$path = 'c:\temp\invalidXml.xml'
try {
$myXml = [xml](Get-Content -Path $path -Raw)
} catch [System.Management.Automation.PSInvalidCastException] {
"'$path' is not a valid XML document"
}
但是,我只希望catch块捕获与将文件内容转换为XML相关的问题;而不是其他类型的转换异常。可以这样做:
$path = 'c:\temp\invalidXml.xml'
try {
$myXml = [xml](Get-Content -Path $path -Raw)
#some other code which may cause a PSInvalidCastException to be thrown. e.g.
#$myDate = [DateTime]'not a date'
} catch [System.Management.Automation.PSInvalidCastException] {
if ($_.Exception.InnerException -as [System.Xml.XmlException]) {
"'$path' is not a valid XML document"
} else {
throw #not the exception we wanted to catch, so throw it back
}
}
$path = 'c:\temp\invalidXml.xml'
try {
$myXml = [xml](Get-Content -Path $path -Raw)
} catch [System.Xml.XmlException] {
"'$path' is not a valid XML document"
}