When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

Copy    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

Copy$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation

$arr.Count
5

If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

Answer from Frode F. on Stack Overflow
🌐
Vexx32
vexx32.github.io › 2020 › 02 › 15 › Building-Arrays-Collections
Building Arrays and Collections in PowerShell
Let's take a look at some fairly ... sound, at least at first glance. So… spot anything amiss? The pattern here is "create the collection object, and then add each item to it one at a time"....
Top answer
1 of 3
352

When using the $array.Add()-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.

$array += $element creates a new array with the same elements as old one + the new item, and this new larger array replaces the old one in the $array-variable

You can use the += operator to add an element to an array. When you use it, Windows PowerShell actually creates a new array with the values of the original array and the added value. For example, to add an element with a value of 200 to the array in the $a variable, type:

Copy    $a += 200

Source: about_Arrays

+= is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:

Copy$arr = 1..3    #Array
$arr += (4..5) #Combine with another array in a single write-operation

$arr.Count
5

If that's not possible, consider using a more efficient collection like List or ArrayList (see the other answer).

2 of 3
185

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

Copy$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

Copy$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

Copy$outItems.ToArray()
Discussions

How do I add to this Collection in Powershell? - Stack Overflow
I'm pulling some data down in a REST API from our ITSM solution, it gets parsed from json and put into an object called $listOfCurrentUsers. I'm then creating an object from data that I pull from A... More on stackoverflow.com
🌐 stackoverflow.com
Adding items to a custom object?

It is important to note that what you are doing is creating a new object, $stuff, with 2 properties: data1 and data2.

What you are showing in your example output is actually what you would be getting from a collection of objects. So, first we will create a collection object. For simplicity's sake, we will just make a standard empty array object to hold the objects in the collection:

$collection = @()

Now, we will add the items one at a time into the collection:

$collection += new-object psobject -property @{data1="foo1";data2="bar1"}
$collection += new-object psobject -property @{data1="foo2";data2="bar2"}
$collection += new-object psobject -property @{data1="foo3";data2="foo3"}

Showing the contents of collection will give us:

$collection
data2           data1
-----            -----
bar1            foo1
bar2            foo2
bar3            foo3

There are ways to make this faster, for instance create the collection as an arraylist and use the .add() method to add objects into the collection: [edit for clarity: By 'faster', I mean in instances where you are working with a large amount of data, not necessarily faster to create the script. For most uses that I'm aware of / have tried, the standard empty array @() will work just fine.]

$collection = new-object system.collections.arraylist
$collection.add(new-object psobject -property @{data1="foo";data2="bar"})

The only downside to using an arraylist is that the .add() method returns the current index that the item is being added at, so adding 5 objects into the collection would show the following in the console:

0
1
2
3
4

To circumvent this, pipe the $collection.add() method to out-null, so that it eats the output:

$collection.add(new-object pscustomobject -property @{data1="foo";data2="bar"}) | out-null

Hope this helps!

More on reddit.com
🌐 r/PowerShell
4
2
February 18, 2016
powershell - Add items into a collection array dynamically - Stack Overflow
Additionally, your solution can be streamlined, because it is both simpler and more efficient to let PowerShell create arrays for you, simply by collecting the output from commands that output multiple objects in a variable. Here's a simplified example that puts it all together: More on stackoverflow.com
🌐 stackoverflow.com
Two ways of creating a new System.Collections.ArrayList object, what's the difference?
Yes, you create an empty array then use it to initialize the variable. Two other ways (System not needed as its namespace is already loaded): [Collections.ArrayList]$list = @() $list = [Collections.ArrayList]::new() New-Object is useful when you need -ComObject, or to dynamically create a type (typename stored as a string that you may not know when writing). It is the 'older' method before powershell had classes built-in. Also, if you create an 'untyped' variable from a cast, you can change its type later on. The first example I posted enforces the type for that variable, it can only be an arraylist. I recommend using the generic types where you can specify the type: [Collections.Generic.List[String]]$list = @() $list = [Collections.Generic.List[Int]]::new() Also save some typing and use a namespace: using namespace System.Collections.Generic [List[String]]$list = @() $list = [List[Int]]::new() And for speed (enumeration access), if the items are unique, try a HashSet: using namespace System.Collections.Generic [HashSet[String]]$list = @() $list = [HashSet[Int]]::new() You should be measuring speed on insertion/removal and access for real world speed tests. And you'll definitely see different results when you go past milestones like 10, 1000, 10000 items (generics are tailored to large datasets). More on reddit.com
🌐 r/PowerShell
11
27
April 7, 2023
🌐
Andreasbijl
andreasbijl.com › powershell-create-collections-of-custom-objects
PowerShell – Create collections of custom objects | AndreasBijl.com
November 25, 2013 - Instead of the above example where it took 4 lines to create an object with 3 properties, this object can be created with all three fields in 1 line. However adding the contents to the fields might still require some additional lines which makes it also end up with 4 lines to create and fill the object. $collectionWithItems = New-Object System.Collections.ArrayList for($i = 0; $i -lt 10; $i++) { $temp = "" | select "Field1", "Field2", "Field3" $temp.Field1 = "Value1" $temp.Field2 = "Value2" $temp.Field3 = "Value3" $collectionWithItems.Add($temp) | Out-Null }
🌐
Practical 365
practical365.com › home › powershell › practical powershell: crafting collections
Practical PowerShell: Crafting Collections | Practical365
June 3, 2025 - It does require PowerShell v7, e.g. $dictionary.Add(‘key’, ‘value’) Finally, I have stored all the code that is mentioned throughout the series in a GitHub repository for your convenience. You can find it here. Tags: .NET Framework, PowerShell, PowerShell Collections · Michel de Rooij, with over 25 years of mixed consulting and automation experience with Exchange and related technologies, is a consultant for Rapid Circle. He assists organizations in their journey to and using Microsoft 365, primarily focusing on Exchange and associated technologies and automating processes using PowerShell or Graph.
🌐
Medium
medium.com › @oakhelloworld › powershell-collection-968226024f38
Powershell: Collection. PowerShell provides a variety of data… | by Oak HelloWorld | Medium
September 28, 2023 - 6. ArrayLists: `System.Collections.ArrayList` is similar to a generic list but allows you to store objects of various types in the same list. $myArrayList = New-Object System.Collections.ArrayList $myArrayList.Add(“String”) $myArrayList.Add(123) 7. Dictionaries (Generic): PowerShell 7 introduced generic dictionaries, which are strongly typed and offer better performance when compared to hash tables.
🌐
Tachytelic
tachytelic.net › home › add items to a powershell array
Add items to a Powershell Array
September 4, 2019 - Here is an example: $names = New-Object System.Collections.ArrayList $names.Add("Paul") $names.Add("John") $names.Add("Simon") $names.Remove("Paul") This method makes it much easier to work with dynamically sized arrays.
🌐
Stack Overflow
stackoverflow.com › questions › 57102462 › how-do-i-add-to-this-collection-in-powershell
How do I add to this Collection in Powershell? - Stack Overflow
I'm then creating an object from data that I pull from Active Directory. It then checks to see if the AD user exists in the $listOfCurrentUsers and if it does, it adds the record ID to the $CAServiceDesk object.
Find elsewhere
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › how to add items to an array in powershell?
How to Add Items to an Array in PowerShell? - SharePoint Diary
September 20, 2025 - To add a value to an array in PowerShell only if it is unique (i.e., if the value doesn’t already exist in the array), you can use a combination of the -notcontains operator and array manipulation.
🌐
Jonathanmedd
jonathanmedd.net › 2014 › 01 › adding-and-removing-items-from-a-powershell-array.html
Adding and Removing Items from a PowerShell Array - Jonathan Medd's Blog
\[System.Collections.ArrayList\]$ArrayList = $Fruits $ArrayList.GetType() Now if we try the previous add and remove methods we are successful: $ArrayList.Add("Kiwi") $ArrayList $ArrayList.Remove("Apple") $ArrayList · Alternatively, if we had stuck with the original Array object we could do the following to ‘add’ an item to it.
🌐
Adam the Automator
adamtheautomator.com › powershell-array
PowerShell Arrays, ArrayLists & Collections: Best Practices
Since a basic array is a collection of fixed size, you cannot modify it. Attempting to use the Add() method with an array that is fixed size will result in an error due to the fixed size. Below you can see a few examples in which you can successfully add items to an array.
Published   April 22, 2025
🌐
Red Gate Software
red-gate.com › home › powershell one-liners: collections, hashtables, arrays and strings
PowerShell One-Liners: Collections, Hashtables, Arrays and Strings | Simple Talk
January 23, 2019 - Entries here also show how to obtain ... well as adding to collections. Once you have a collection chances are you might want to re-order it per the needs of your application. You can do this with derived properties almost as easily as with simple named properties. The last few entries show how to apply sorting to file contents as well. If you are used to relying on LINQ-to-Object operators in C# so much that you may are almost compelled to reject PowerShell out of hand, ...
🌐
Reddit
reddit.com › r/powershell › adding items to a custom object?
r/PowerShell on Reddit: Adding items to a custom object?
February 18, 2016 -

I know not a lot about custom objects. I want to do something easy. At this point I'm just making a hash table, adding content to it, then making a new custom object that reflects the data in that hash table. I want to be able to keep adding data to this custom object moving forward. Something like this...

$things=@{}
$things.data1="foo"
$things.data2="bar"

$stuff=new-object psobject -property $things

$stuff
data2            data1
-----              -----
bar                foo                                                                                       

OK so far. Now I want to add more. How do I get to this?

$stuff
data2            data1
-----              -----                                                                                     
bar                foo
morebar        fooALLTHETIME 
Top answer
1 of 3
5

It is important to note that what you are doing is creating a new object, $stuff, with 2 properties: data1 and data2.

What you are showing in your example output is actually what you would be getting from a collection of objects. So, first we will create a collection object. For simplicity's sake, we will just make a standard empty array object to hold the objects in the collection:

$collection = @()

Now, we will add the items one at a time into the collection:

$collection += new-object psobject -property @{data1="foo1";data2="bar1"}
$collection += new-object psobject -property @{data1="foo2";data2="bar2"}
$collection += new-object psobject -property @{data1="foo3";data2="foo3"}

Showing the contents of collection will give us:

$collection
data2           data1
-----            -----
bar1            foo1
bar2            foo2
bar3            foo3

There are ways to make this faster, for instance create the collection as an arraylist and use the .add() method to add objects into the collection: [edit for clarity: By 'faster', I mean in instances where you are working with a large amount of data, not necessarily faster to create the script. For most uses that I'm aware of / have tried, the standard empty array @() will work just fine.]

$collection = new-object system.collections.arraylist
$collection.add(new-object psobject -property @{data1="foo";data2="bar"})

The only downside to using an arraylist is that the .add() method returns the current index that the item is being added at, so adding 5 objects into the collection would show the following in the console:

0
1
2
3
4

To circumvent this, pipe the $collection.add() method to out-null, so that it eats the output:

$collection.add(new-object pscustomobject -property @{data1="foo";data2="bar"}) | out-null

Hope this helps!

2 of 3
4
$stuff = @()

$stuff += New-Object psobject -prop @{
    data1 = 'foo'
    data2 = 'bar'
}

$stuff += New-Object psobject -prop @{
    data1 = 'morebar'
    data2 = 'fooALLTHETHINGS'
}

# and if you want to add a new property, these both achieve the same result
$stuff | % {$_ | Add-Member -MemberType NoteProperty -Name data3 -Value 'new'}
$stuff = $stuff | % {$_ | select *, @{n='data4';e={'somethingelse'}}}

# but then when you want to add another object should specify all the properties

$stuff += New-Object psobject -prop @{
    data1 = 'test1'
    data2 = 'test2'
    data3 = 'test3'
    data4 = 'test4'
}

$stuff

*edited

Top answer
1 of 2
2

The problem is that you're updating the very same object, $Table, over and over, and adding references to that same object to the output array, $ToWrite - all of whose elements therefore end up pointing to the one and only $Table object, whose property values at that point contain the ones that were assigned in the last iteration.

The problem is explained in detail in this answer, which shows a possible solution using custom classes, available in PowerShell v5 and above.

A solution without custom classes requires you to clone your custom $Table object in each iteration:

# Create a new instance with the same properties:
$Table = $Table.psobject.Copy()

Note: This cloning technique only works as expected with custom objects, i.e., instances of [System.Management.Automation.PSCustomObject], such as created by the Select-Object cmdlet and literal syntax [pscustomobject] @{ ... }

That said, since you're assigning to all properties of your custom object in your loop, there is no benefit to creating a template object up front - instead, simply use literal custom-object creation syntax [pscustomobject] @{ ... } (PSv3+) inside your loop, which implicitly creates a new instance in every iteration.


Additionally, your solution can be streamlined, because it is both simpler and more efficient to let PowerShell create arrays for you, simply by collecting the output from commands that output multiple objects in a variable.

Here's a simplified example that puts it all together:

# Loop over the input and instantiate a new custom object
# in each iteration, then let PowerShell collect the results
# in array variable $ToWrite
[array] $ToWrite = 1..3 | ForEach-Object {
  # Instantiate and output a new custom object in each iteration.
  [pscustomobject] @{
    PropA = "ValueA-$_"
    PropB = "ValueB-$_"
  }
}

# Output the resulting array
$ToWrite

Note: The [array] type constraint is only needed if you need to ensure that $ToWrite is always an array; without it, if there happened to be just a single loop iteration and therefore output object, $ToWrite would store that output object as-is, not wrapped in an array (this behavior is fundamental to PowerShell's pipeline).

The above yields the following, showing that distinct objects were created:

PropA    PropB
-----    -----
ValueA-1 ValueB-1
ValueA-2 ValueB-2
ValueA-3 ValueB-3
2 of 2
1

To illustrate - big caveat here, I'm at home so can't test any of this but it should give you an idea:

$AllPOCs = Get-ADGroupMember 'ALL POC'

$Table = $AllPOCs | ForEach-Object {
    $Name = $_.SamAccountName
    $TestPOC = Invoke-Sqlcmd -Query "SELECT * FROM TABLE WHERE CLIENT = '$Name'" -ServerInstance "SERVER\INSTANCE"

    If($TestPOC -eq $null) {
        $POC = get-aduser $Name -Properties * | select -Property SamAccountName, GivenName, Surname, SID, EmailAddress 
        $SEQUENCE = Invoke-Sqlcmd -Query "Select TABLEFIELD FROM DATABASE WHERE NAME = 'FIELDID'" -ServerInstance "SERVER\INSTANCE"
        $SEQUENCE = $SEQUENCE.RECNUM + 1
        [pscustomobject]@{SEQUENCE = $SEQUENCE;
                        LASTUSER = 'SYSTEMACCOUNT';
                        GROUP = 1;
                        CLIENT = $_.ToUpper();
                        FNAME = $_.GivenName.ToString();
                        Name = $_.surname.ToString();
                        EmailID = 'SMTP:{' + $_.EmailAddress.ToString() + '}' + $_.EmailAddress.ToString();
                        USEDEPT = 0;
                        USELOCATION = 0;
                        CREATEDFROMSSD = 0;
                        DISPLAYCLIENTCOMMENTS = 0;
                        _INACTIVE_ = 0;
                        WINUSERID = '\DOMAIN' + $_.SamAccountName.ToString();
                        SELFSERVICEACCESS = 'TYPE';
                        SELFSERVICELICENSE = 1;
                        WIAENABLED = 1;
                        SID = $_.SID.ToString()}
        $SEQUENCE += 1
    }
}

The above can also be simplified, but I've tried to keep it similar to your exisitng code

🌐
Reddit
reddit.com › r/powershell › two ways of creating a new system.collections.arraylist object, what's the difference?
r/PowerShell on Reddit: Two ways of creating a new System.Collections.ArrayList object, what's the difference?
April 7, 2023 -

I've come across two ways of creating a new System.Collections.ArrayList object:

$arrA = New-Object System.Collections.ArrayList
$arrB = [System.Collections.ArrayList]@() 

I have two questions:

  1. for arrB, if I'm reading this right, @() is creating an empty array and then it's being cast into [System.Collections.ArrayList]?

  2. Working with the created object is the same for me either way, but are there any differences I may be missing?

I made a quick test and casting was faster, but the difference is only noticeable when creating new arrays reaches the hundreds of thousands to millions (tested on an old A10-7870k). Doesn't really matter when I'm creating one array, but I thought it was mildly interesting.

$max = 100000
$ticksStart = (Get-Date).Ticks
for ($i = 0; $i -lt $max; $i++)
{
	$arrA = New-Object System.Collections.ArrayList
}
$ticksEnd = (Get-Date).Ticks
Write-Host 'arrA (ticks)	: ' ($ticksEnd - $ticksStart)

$ticksStart = (Get-Date).Ticks
for ($i = 0; $i -lt $max; $i++)
{
	$arrB = [System.Collections.ArrayList]@()
}
$ticksEnd = (Get-Date).Ticks
Write-Host  'arrB (ticks)	: ' ($ticksEnd - $ticksStart)
arrA (ticks)	:  64310000
arrB (ticks)	:  3170000
🌐
Delft Stack
delftstack.com › home › howto › powershell › powershell add object to array
How to Add Objects to an Array of Objects in PowerShell | Delft Stack
February 12, 2024 - In this example, we have an existing ... elements 4, 5, and 6. By using the += operator, we add the new elements to the existing array, resulting in an updated array containing 1, 2, 3, 4, 5, and 6. The ArrayList class in PowerShell ...
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › configurationmanager › new-cmdevicecollection
New-CMDeviceCollection (ConfigurationManager) - Configuration Manager | Microsoft Learn
To add members to the device collection, use one of the following membership rule cmdlets: ... For more information, see How to create collections in Configuration Manager. ... Run Configuration Manager cmdlets from the Configuration Manager site drive, for example PS XYZ:\>. For more information, see getting started.
🌐
Powershell Commands
powershellcommands.com › collections-in-powershell
Mastering Collections in PowerShell: A Quick Guide
November 10, 2024 - Here's a simple example of creating an array collection in PowerShell: # Creating an array collection $fruitCollection = @('Apple', 'Banana', 'Cherry') # Displaying the collection $fruitCollection · Collections in PowerShell refer to data ...
🌐
Prajwal Desai
prajwaldesai.com › home › add multiple devices to sccm collection using powershell
Add Multiple Devices to SCCM collection using PowerShell » Prajwal Desai
March 2, 2020 - After creating the target device collection, prepare a TXT file that contains all devices that you wish to add to device collection. In this example, the file name is List_computers.txt and contains the following devices. On the top ribbon of the ConfigMgr console, click to the blue arrow and click Connect via Windows PowerShell.