How to add a custom property to a PowerShell array?

Question:

Say I have a PowerShell array $Sessions = @() which I am going to fill with PSCustomObjects. How can I add a custom property to the array itself? E.g. so I can have $Sessions.Count which is built-in and $Sessions.Active which I want to set to the active session count.

I know that I can add properties to PSCustomObjects (in a dirty way) with

but though doing so on an array would not result in the property being added.

So how can I achieve my goal? Is there any way to create a custom array?

Answer:

The answer to your question as stated would be to just use Add-Member on the array object.

Adding a property to each element after you created the object is similar.

This of course comes with a warning (that I forgot about). From comments

Beware, though, that appending to that array ($sessions += …) will replace the array, thus removing the additional property.

Ansgar Wiechers

Depending on your use case there are other options to get you want you want. You can save array elements into distinct variables:

Or you could still store your state property and post process with Where-Object as required:

To avoid the destroying / recreating array issue, which can be a performance hog, you could also use an array list instead.

Notice that the array had its member added then we added its elements.

Source:

How to add a custom property to a PowerShell array? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply