Reading XML file using Powershell specification

Powershell is like barfing in an XML file with a unicode specification - code:

$xml = [xml]{ get-content $filename }

explodes "Data at the root level is invalid."

Is there an easy way to do this without loading the contents of the file?

+3
source share
1 answer

You are trying to convert a script block to XML here. Use ()instead {}:

$xml  = [xml] (gc $filename)

In fact, the error message tells you so much already:

PS Home:\> $xml = [xml]{gc test.xml}
Cannot convert value "gc test.xml" to type "System.Xml.XmlDocument". Error: "Data at the root level is invalid. Line 1,
 position 1."
At line:1 char:13
+ $xml = [xml] <<<< {gc test.xml}
    + CategoryInfo          : NotSpecified: (:) [], RuntimeException
    + FullyQualifiedErrorId : RuntimeException

Have you noticed how the contents of the script message is displayed in the error message?

+6
source

All Articles