Casting in powershell ? Weird syntax?
$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
.