PowerShell custom table question

Status
Not open for further replies.

RojBlake

Ars Legatus Legionis
48,129
Subscriptor
I'm trying to create a custom table, i.e. I want to decide the number of columns, give titles to the columns, add rows of data and then be able to query it. For example, to get the third row I could do "$table[2]". Or to get the value of just the "CPU" column of the third row I could do "$table[2].cpu".

I know I can use hash tables to effectively create a two column table. But I'm getting stuck down the google hole trying to figure out how to make bigger tables than that.

For example, I can do this...
Code:
$obj2 = New-Object -TypeName PSObject -Property @{
    Item = "Apple"
    Color = "Red"
    Size = "Large"
    }
$obj2 | ft


Color Item  Size 
----- ----  ---- 
Red   Apple Large
...which works perfectly for that one row. But how do I add another row?

Or is there a better way to do it?
 

Klockwerk

Ars Praefectus
3,763
Subscriptor
Sounds like you're looking at creating a custom powershell object. Bear in mind there are many, many different ways to create new objects, and I don't have my examples in front of me. I've run this up in the PowerShell ISE:

====

$Array_of_new_objects = @()

$my_object = New-Object System.Object
$my_object | Add-Member -MemberType NoteProperty -Name "Item" -Value "Apple"
$my_object | Add-Member -MemberType NoteProperty -Name "Color" -Value "Red"
$my_object | Add-Member -MemberType NoteProperty -Name "Size" -Value "Small"

$my_other_object = New-Object System.Object
$my_other_object | Add-Member -MemberType NoteProperty -Name "Item" -Value "Pear"
$my_other_object | Add-Member -MemberType NoteProperty -Name "Color" -Value "Green"
$my_other_object | Add-Member -MemberType NoteProperty -Name "Size" -Value "Smallish"

$Array_of_new_objects += $my_object
$Array_of_new_objects += $my_other_object

$Array_of_new_objects

ForEach ($fruit in $Array_of_new_objects)
{
$fruit.Color
}
====

Result:

====
PS C:\Users\XXX> $Array_of_new_objects = @()

$my_object = New-Object System.Object
$my_object | Add-Member -MemberType NoteProperty -Name "Item" -Value "Apple"
$my_object | Add-Member -MemberType NoteProperty -Name "Color" -Value "Red"
$my_object | Add-Member -MemberType NoteProperty -Name "Size" -Value "Small"

$my_other_object = New-Object System.Object
$my_other_object | Add-Member -MemberType NoteProperty -Name "Item" -Value "Pear"
$my_other_object | Add-Member -MemberType NoteProperty -Name "Color" -Value "Green"
$my_other_object | Add-Member -MemberType NoteProperty -Name "Size" -Value "Smallish"

$Array_of_new_objects += $my_object
$Array_of_new_objects += $my_other_object

$Array_of_new_objects

ForEach ($fruit in $Array_of_new_objects)
{
$fruit.Color
}


Item Color Size
---- ----- ----
Apple Red Small
Pear Green Smallish
Red
Green



PS C:\Users\XXX>

====
 

RojBlake

Ars Legatus Legionis
48,129
Subscriptor
Ah, I didn't realize you could add that kind of object to a basic array. That works perfectly. Thanks!

Looks like you can do it with 'New-Object PSObject' and get the same (visual) result. I'm not sure what the technical difference is between 'PSObject' and 'System.Object', though:

Code:
$obj1 = New-Object -TypeName PSObject

$obj1.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                         
-------- -------- ----                                     --------                                                                                                                         
True     False    PSCustomObject                           System.Object
Code:
$obj1 = New-Object -TypeName System.Object

$obj1.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                         
-------- -------- ----                                     --------                                                                                                                         
True     True     Object

Also, constructing the table this way works too...almost:

Code:
$table = @()
$obj1 = New-Object -TypeName PSObject -Property @{
    Item = "Apple"
    Color = "Red"
    Size = "Large"
    }
$obj2 = New-Object -TypeName PSObject -Property @{
    Item = "Pear"
    Color = "Green"
    Size = "Smallish"
    }
$table += $obj1
$table += $obj2
$table

Color Item  Size    
----- ----  ----    
Red   Apple Large   
Green Pear  Smallish

As you can see, in this version the column names get switched to alphabetical order. I'm not sure how to fix that.

So, I like your method better. :)
 

Pont

Ars Legatus Legionis
26,160
Subscriptor
[pscustomobject] is your friend, too.

Code:
$foo = [pscustomobject]@{"col1"="foo";"col2"="bar";"col3"="baz"}
$foo | format-table

As you can see, in this version the column names get switched to alphabetical order. I'm not sure how to fix that.
You can pipe to format-table explicitly rather than implicitly.

Code:
$mytabledata | Format-Table -Property col1,col2,col3,col4
 

RojBlake

Ars Legatus Legionis
48,129
Subscriptor
Cool!

Also, it looks like this...

Code:
$foo = [pscustomobject]@{"col1"="foo";"col2"="bar";"col3"="baz"}
$foo | format-table

...is basically identical to this...

Code:
$foo = New-Object -TypeName PSObject -Property @{"col1"="foo";"col2"="bar";"col3"="baz"}
$foo | format-table

...except your version respects explicit column order by default. :cool:
 

Cookie.Monster

Ars Scholae Palatinae
666
pscustomobject is the preferred route - it orders things, and is way faster. You can also set custom types. Only downside is that you need PowerShell v3 or later... but realistically, you should be on the latest, if you value security, automation, efficiency, etc.

Some examples:

Code:
# Create an object with your own type...
$o = [pscustomobject]@{
    PSTypeName = 'My.Type'
    A = 1
    B = 2
}

$o | Get-Member

<#
   TypeName: My.Type

    ...
#>

# Example function requiring your custom type
function Test-Example {
    [cmdletbinding()]
    param(
        [PSTypeName('My.Type')]
        $a
    )
    $a
}

# With out custom typed object, it works!
Test-Example -a $o

<#
    A B
    - -
    1 2
#>

# With the incorrect type, it fails
$WrongType = [pscustomobject]@{
    Blah = 5
}
Test-Example -a $WrongType

<#
    Test-Example : Cannot bind argument to parameter 'a', because PSTypeNames of the argument do not match the PSTypeName required by the parameter: My.Type.
    At line:1 char:17
    + Test-Example -a $WrongType
    +                 ~~~~~~~~~~
        + CategoryInfo          : InvalidArgument: (:) [Test-Example], ParameterBindingArgumentTransformationException
        + FullyQualifiedErrorId : MismatchedPSTypeName,Test-Example
#>

Cheers!
 
Status
Not open for further replies.