Bee_Riii
Bee_Riii

Reputation: 1039

Powershell - how do I add multiple objects to a property on a custom object?

I'm currently working on a project to document a bunch of SSIS packages. Since the packages are stored in XML it's pretty easy to import the package as XML and I can get to the information I want.

What I think I want to do is capture key information in objects with my own defined properties so at the end I can export the object in a format of my choosing.

I'm trying to get my head around properties of objects and how I would assign multiple objects to a property.

So for instance I create an object $Package that represents the SSIS package. That package would have some top level properties for instance Name, Path, and Type all stored as strings. But then there are 5 ConnectionManagers in the package so I want to assign 5 objects representing the ConnectionManagers to $Package. Now one of the connection managers has 2 expressions so I want to reference 2 objects for the expression property under the ConnectionManager Property.

How do I add a collection of objects as a property of an existing custom object and do I have to add them all at once or can I add to that collection?

Upvotes: 0

Views: 2597

Answers (2)

user2674513
user2674513

Reputation:

With respect to Bee_Riii's comment, you do not have to include all properties while defining an object. You can add a new array using Add-Member.

Add-Member -InputObject $p -NotePropertyName myVariables -NotePropertyValue @(1,2,3)

You might also choose to use an existing value.

$existingValue = @(1,2,3)
   
Add-Member -InputObject $p -NotePropertyName myVariables -NotePropertyValue $existingValue

Here I use the variable name myVariables as a precaution. Generic names like name and variable often collide with existing properties. I formed the habit of prepending 'my' to these names to avoid collisions.

You might find these resources useful:

Upvotes: 2

WaitingForGuacamole
WaitingForGuacamole

Reputation: 4301

$p = [PSCustomObject] @{
  Name = "packageName"
  Path = "packagePath"
  Type = "packageType"
  ConnectionManagers = @()
 }

$p.ConnectionManagers += [PSCustomObject] @{
  Name = "managerName"    
  Connection = "connectionString"
 }

sets up a package with an empty connection manager list, then adds a connection manager object to it.

If you already have a list of connection managers in a variable, replace the [PSCustomObject] in that last assignment with the variable containing the list you want to add

Upvotes: 0

Related Questions