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
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.
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.
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.
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.
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
}
System.Management.Automation.ArgumentTransformationMetadataException
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With