Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting in PowerShell. Weird syntax

Tags:

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; 
like image 879
monojohnny Avatar asked Jul 27 '12 09:07

monojohnny


People also ask

Why we use $_ in PowerShell?

$_ 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.

What is casting in PowerShell?

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

What does @() mean in PowerShell?

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.

How do I convert an object to a string in PowerShell?

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.


1 Answers

$x = [xml](Get-Content myxml.xml) 
like image 51
David Brabant Avatar answered Sep 18 '22 06:09

David Brabant