PowerShell – PSObject Collection


I needed to create a diagram for further work so I wanted to use PowerShell output for that. But how to create self-object as PSObject?

PSObject can be created by:

$Object1 = New-Object PSObject
$Object1 | add-member -Type NoteProperty -name "Name" -value "Phill"
$Object1 | add-member -Type NoteProperty -name "Alias" -value "Phoo"

Another object:

$Object2 = New-Object PSObject
$Object2 | add-member -Type NoteProperty -name "Name" -value "John"
$Object2 | add-member -Type NoteProperty -name "Alias" -value "Jahoo"

How to marge two or more objects? We need to create collection and load required objects:

[PSObject[]] $Collection1 = @()
$Collection=$Object1,$Object2

What is output for case above?

$Collection | fl

Name : Phill
Alias : Phoo

Name : John
Alias : Jahoo

Collection can be created dynamically for example like this:

[PSObject[]] $Collection = @()
for($i=1;$i -le 3;$i++){
$Object = @()
$Object = New-Object PSObject
$Object | add-member -Type NoteProperty -name "Number" -value "$i"
$Object | add-member -Type NoteProperty -name "MyNumber" -value "My$i"
$Collection+=$Object
}
$Collection|fl

The output is following:

Number : 1
MyNumber : My1 

Number : 2
MyNumber : My2

Number : 3
MyNumber : My3
Advertisements

One thought on “PowerShell – PSObject Collection

  1. Hi,
    may I ask some question?
    Why do you think a PSObject is better than an simple hastable?
    Would it be possible to add to a hashtable and/or a PSObject complex objects like:
    $hash = { “Socket = New-Object System.Net.Sockets.TcpClient $IP, $PORT; … }
    Would it be better to store this in a PSObject like (using your example from above):
    $Object | add-member -Type NoteProperty -name “Socket” -value $(New-Object System.Net.Sockets.TcpClient $IP, $PORT)
    (would that be correct?)
    Thanks a lot in advance!
    Carl

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s