Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: Add objects to an array of objects

I have this script where I want to add an object to an array called $Target in every foreach.

foreach ($Machine in $Machines) {   $TargetProperties = @{Name=$Machine}     $TargetObject = New-Object PSObject –Property $TargetProperties   $Target= @()   $Target =  $TargetObject } 

I know it is not working because $Target = $TargetObject makes it equal to the same object.

How can I append to the array instead of replace?

like image 683
Ricardo Polo Jaramillo Avatar asked Jun 29 '12 17:06

Ricardo Polo Jaramillo


People also ask

How do you add an object to an array of objects?

To add items and objects to an array, you can use the push() function in JavaScript. The push() function adds an item or object at the end of an array. For example, let's create an array with three values and add an item at the end of the array using the push() function.

How do you append to a list in PowerShell?

The + operator in PowerShell is used to add items to various lists or to concatenate strings together. To add an item to an array, we can have PowerShell list all items in the array by just typing out its variable, then including + <AnotherItemName> behind it.

How do you assign a value to an array in PowerShell?

You can use the += operator to add an element to an array. The following example shows how to add an element to the $a array. When you use the += operator, PowerShell actually creates a new array with the values of the original array and the added value.

How do I add a value to an object in PowerShell?

To use Add-Member , pipe the object to Add-Member , or use the InputObject parameter to specify the object. The MemberType parameter indicates the type of member that you want to add. The Name parameter assigns a name to the new member, and the Value parameter sets the value of the member.


1 Answers

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

like image 173
SpellingD Avatar answered Sep 19 '22 22:09

SpellingD