11

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

15

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
}
Sign up to request clarification or add additional context in comments.

Comments

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 Comments

arg, okay I added a one-liner solution.
Nice! I liked the loop assignment as well.
+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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.