Does the latest version of Powershell have the ability to do something like JavaScript's:
var point = new Object();
point.x = 12;
point.y = 50;
If not, what is the equivalent or workaround?
UPDATE
Read all comments
What is a PowerShell object? A PowerShell object is some thing that was created by a developer. Objects have a name, properties, and methods. Properties describe the object and methods are actions you can perform on it.
$_ 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.
To get the properties of an object, use the Get-Member cmdlet. For example, to get the properties of a FileInfo object, use the Get-ChildItem cmdlet to get the FileInfo object that represents a file. Then, use a pipeline operator ( | ) to send the FileInfo object to Get-Member .
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 syntax is not directly supported by the functionality is there via the add-member cmdlet's. Awhile ago, I wrapped this functionality in a general purpose tuple function.
This will give you the ability to one line create these objects.
$point = New-Tuple "x",12,"y",50
Here is the code for New-Tuple
function New-Tuple()
{
param ( [object[]]$list= $(throw "Please specify the list of names and values") )
$tuple = new-object psobject
for ( $i= 0 ; $i -lt $list.Length; $i = $i+2)
{
$name = [string]($list[$i])
$value = $list[$i+1]
$tuple | add-member NoteProperty $name $value
}
return $tuple
}
Blog Post on the subject: http://blogs.msdn.com/jaredpar/archive/2007/11/29/tuples-in-powershell.aspx#comments
For simple ways, first, is a hashtable (available in V1)
$obj = @{}
$obj.x = 1
$obj.y = 2
Second, is a PSObject (easier in V2)
$obj = new-object psobject -property @{x = 1; y =2}
It gives you roughly the same object, but psobjects are nicer if you want to sort/group/format/export them
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