How to Initializing an Array of Custom Objects in PowerShell

When working with custom objects in PowerShell, initializing an array of such objects might initially seem daunting. However, it's a straightforward process once you understand the syntax.

To initialize an array of custom objects, you can use the @() syntax in conjunction with @{} for each object within the array.

Here's a breakdown of the syntax:

$groups = @(
    @{ Name = "First"; Property1 = Value1; Property2 = Value2 },
    @{ Name = "Second"; Property1 = Value3; Property2 = Value4 },
    # Add more objects as needed

In the above example:

  • $groups is the variable storing the array of custom objects.
  • @() encapsulates the array.
  • @{} defines each custom object within the array.
  • Inside each @{}, you specify the properties and their respective values for each custom object.

For instance, Name, Property1, and Property2 are properties of the custom objects, and you assign values to them accordingly.

By following this syntax, you can easily initialize an array of custom objects in PowerShell, making your scripts more efficient and readable.


Leave a Comment

All fields are required. Your email address will not be published.