25

Reading XML from a file into a variable can be done like this:

[xml]$x = Get-Content myxml.xml

But why not:

$x = [xml]Get-Content myxml.xml

Which gives:

Unexpected token 'Get-Content' in expression or statement.
At line:1 char:20
+ $x=[xml]get-content <<<<  myxml.xml
    + CategoryInfo          : ParserError: (get-content:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

That is, why is the cast operation done on the left-hand side of the equals sign? Typically in programming languages the casting is done on the right-hand side like (say) in Java:

a = (String)myobject;

2 Answers 2

36
$x = [xml](Get-Content myxml.xml)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks ! Anybody know why these brackets are needed ?
Because get-content myxml.xml is an expression; (get-content myxml.xml) is an object. You need to have an object to begin with to cast it to something else!
To add to this a little, the parentheses around the cmdlet forces the expression to resolve. Then, the resolved expression, which is now an object, is passed into the cast operator.
12

In PowerShell everything is an object. That includes the cmdlets. Casting is the process of converting one object type into another.

What this means for casting is that, like in math, you can add in unnecessary brackets to help you clarify for yourself what exactly is happening. In math, 1 + 2 + 3 can become ((1 + 2) + 3) without changing its meaning.

For PowerShell the casting is performed on the next object (to the right), so $x = [xml] get-content myxml.xml becomes $x = ([xml] (get-content)) myxml.xml. This shows that you are trying to cast the cmdlet into an xml object, which is not allowed.

Clearly this is not what you are trying to do, so you must first execute the cmdlet and then cast, AKA $x = [xml] (get-content myxml.xml). The other way to do it, [xml] $x = get-content myxml.xml, is declaring the variable to be of the type xml so that whatever gets assigned to it (AKA the entire right-hand side of the equal sign) will be cast to xml.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.