简体   繁体   中英

Casting in PowerShell. Weird syntax

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;
$x = [xml](Get-Content myxml.xml)

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM