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;
$_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object . But it can be used also in other types of expressions, for example with Select-Object combined with expression properties.
In PowerShell everything is an object. That includes the cmdlets. Casting is the process of converting one object type into another.
Array subexpression operator @( )Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. PowerShell Copy.
The Out-String cmdlet converts input objects into strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the Stream parameter to direct Out-String to return one line at a time or create an array of strings.
$x = [xml](Get-Content myxml.xml)
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