Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PsObject array in powershell

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.

like image 288
Adeel ASIF Avatar asked Jun 08 '16 14:06

Adeel ASIF


2 Answers

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
}
like image 83
briantist Avatar answered Nov 20 '22 05:11

briantist


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';}}
like image 25
Martin Brandl Avatar answered Nov 20 '22 04:11

Martin Brandl