Why PS Custom Object?

Hi Sankhadip,

As for your first question, PSCustom objects have many features which hashtables do not have. Before talking about the features, there are also some functional “gotchas” when trying to use just hashtables rather than PSCustom objects for your generic objects. Here is an example:

$hashTableObject = @{}

$hashTableObject.Name = "Name"
$hashTableObject.Location = "Home"

$hashTableObject # This prints showing the values as expected.
$hashTableObject | ft Name, Location # This does not show the columns as expected. Someone with an "object" would expect to see the name and location property values printed.

$psObject = [PSCustomObject] @{Name="Name";Location="Home"}
$psObject | ft Name, Location #prints as expected.

In addition to avoiding issues like above where the hashtable object does not behave as one might expect, PSCustomobjects provides you with the ability to associate TypeNames and default display properties to the object. This lets you do many things, the most common of which is to control which properties of the object are displayed by default when you print it to the screen. This can be very useful for giving a friendly view of an object while still having many additional, properties available off the object which are not usually read by a human. You can also do many other things once an object has a typename (TypeNames.Insert(0, “MyType”)) see https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_types.ps1xml?view=powershell-6 for more information.

As to your second question, you can add to a hashtable simply by adding a key:

$myHashTable["Key"] = $value

#for example:
$myHashTable = @{}
1..10 | % { $myHashTable[$_] = "Test$_"} # loop through numbers 1 to 10 and add 10 keys to the hashtable.
$myHashTable # contents are 10 items with the value Test(Num)