Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

UPDATE
Read all comments

like image 679
BuddyJoe Avatar asked Mar 13 '09 21:03

BuddyJoe


People also ask

What are the objects in PowerShell?

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.

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.

How do I see attributes of an object in PowerShell?

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 .

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.


2 Answers

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

like image 79
JaredPar Avatar answered Oct 13 '22 18:10

JaredPar


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

like image 21
mrwaim Avatar answered Oct 13 '22 16:10

mrwaim