Powershell – Structs or Objects in Powershell 2


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?

Read all comments

Best Solution

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