Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 271
Adrian Wright Avatar asked May 01 '12 02:05

Adrian Wright


People also ask

How does exception handling work in PowerShell?

The way exception handling works in PowerShell (and many other languages) is that you first try a section of code and if it throws an error, you can catch it. Here is a quick sample. The catch script only runs if there's a terminating error.

How do I find an error exception in PowerShell?

As you can see, that exception is now being handled differently than if it was just another exception. The last way to find an error exception is by iterating through all of the currently loaded exceptions in PowerShell by getting all of the exported types of each assembly.

Why are PowerShell errors and exceptions non-terminating?

Because of this operational nature, PowerShell errors and exceptions are typically non-terminating. 1/0;Write-Host 'Hello, will I run after an error?' The above example is a classic divide by zero error. Because dividing by zero is not possible, this should throw an exception.

How do you handle error handling in PowerShell?

In PowerShell, the error handling is done through trial and catch blocks. The try block will have the code, that may likely throw an error. The catch block contains the code or action to be executed in case of an error that is thrown by the try block. Additionally, a final block can be used to free up the resources.


2 Answers

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
}
like image 193
JPBlanc Avatar answered Sep 30 '22 19:09

JPBlanc


System.Management.Automation.ArgumentTransformationMetadataException

like image 20
Adrian Wright Avatar answered Sep 30 '22 17:09

Adrian Wright