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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With