PsObject array in powershell

Adeel ASIF picture Adeel ASIF · Jun 8, 2016 · Viewed 18.6k times · Source

This is my code :

$a = @()

for ($i = 0; $i -lt 5; $i++)
{

$item = New-Object PSObject
$item | Add-Member -type NoteProperty -Name 'Col1' -Value 'data1'
$item | Add-Member -type NoteProperty -Name 'Col2' -Value 'data2'
$item | Add-Member -type NoteProperty -Name 'Col3' -Value 'data3'
$item | Add-Member -type NoteProperty -Name 'Col4' -Value 'data4'

$a += $item
}

With this code I'm able to have a result like this:

Col1 Col2 Col3 Col4
---- ---- ---- ----
   0    1    2    3
   1    2    3    4
   2    3    4    5
   3    4    5    6
   4    5    6    7

Well, it's good, but how to achieve it more simply and more proper? Is there a way to create Array PsObject maybe?

I'm using Powershell v4.

Answer

briantist picture briantist · Jun 8, 2016

There's nothing wrong with what you're doing, but you can take advantage of a few things.

The -PassThru parameter on Add-Member will return the object itself, so you can chain them:

$a = @()

for ($i = 0; $i -lt 5; $i++)
{
    $item = New-Object PSObject |
    Add-Member -type NoteProperty -Name 'Col1' -Value 'data1' -PassThru |
    Add-Member -type NoteProperty -Name 'Col2' -Value 'data2' -PassThru |
    Add-Member -type NoteProperty -Name 'Col3' -Value 'data3' -PassThru |
    Add-Member -type NoteProperty -Name 'Col4' -Value 'data4' -PassThru

    $a += $item
}

You can provide a [hashtable] of properties to initially add:

$a = @()

for ($i = 0; $i -lt 5; $i++)
{
    $item = New-Object PSObject -Property @{
        Col1 = 'data1'
        Col2 = 'data2'
        Col3 = 'data3'
        Col4 = 'data4'
    }

    $a += $item
}

Similarly, you can use the [PSCustomObject] type accelerator:

$a = @()

for ($i = 0; $i -lt 5; $i++)
{
    $item = [PSCustomObject]@{
        Col1 = 'data1'
        Col2 = 'data2'
        Col3 = 'data3'
        Col4 = 'data4'
    }

    $a += $item
}