10

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.

2 Answers 2

12

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
}
8

I like the PSCustomObject cast to a hashtable:

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

You can just assign the for loop to $a


Or in a one-liner:

$a = 1 .. 5 | % { [PSCustomObject] @{Col1 = 'data1'; Col2 = 'data2';Col3 = 'data3';Col4 = 'data4';}}
3
  • arg, okay I added a one-liner solution. Jun 8, 2016 at 14:31
  • Nice! I liked the loop assignment as well.
    – briantist
    Jun 8, 2016 at 14:32
  • +1 for a sensible one-liner. So many people seem to go nuts with 'em but this is a nice example with high readability in my book.
    – notjustme
    Jun 10, 2016 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.