🌐
SPGuides
spguides.com › powershell-arraylist
PowerShell ArrayList [Create and Use]
March 26, 2025 - Read Split an Array into Smaller Arrays in PowerShell · Iterating over an ArrayList is simple using a foreach loop in PowerShell.
🌐
PDQ
pdq.com › blog › how-to-use-foreach-in-powershell
How to use Foreach in PowerShell | PDQ
October 9, 2025 - $ActionHero = Import-CSV "C:\Temp\john.csv" $FinalList = New-Object 'System.Collections.ArrayList' foreach($Hero in $ActionHero){ If($Hero.FirstName -eq "John"){ $FinalList.Add($Hero) > $null } } This option takes each hero named John and builds a new collection that looks like this. We can take that array and build a new CSV with only the data we want. Having PowerShell there to clean up old or junk data and whittling it down to what is relevant is very valuable for creating colorful charts and graphs that management can "ooh" and "aah" over, making you look like a rock star.
Discussions

How to update an arraylist inside a foreach -parallel
Oof that is some ps1 era code. You don't want to use it at all. Let powershell do the collection for you. Put the object into the output stream so you can assign the results to a variable. $resultlist = $OPenFiles | foreach-object -parallel { # ... [pscustomobject]@{ Role = $fsrole Sharename = $sharename # etc } } More on reddit.com
🌐 r/PowerShell
14
7
May 17, 2023
Loop with foreach removing from arraylist.
I think this should fix your problem $Laptops = ((Get-ADComputer -Filter {Name -like "COMP*"}).name) $TempTops = @() $Logfile = "C:\Temp\EXPORT\LocalAdminZLE $(get-date -f yyyy-MM-dd).csv" while ($Laptops) { foreach ($laptop in $laptops) { $C = Get-LocalGroup -Computername $laptop -Group Administrators if($C) { $C | Export-Csv $Logfile -Append $TempTops += $laptop } $C = $null } $Laptops = Compare-Object $Laptops $TempTops | where {$_.sideindicator -eq "<="} | select -ExpandProperty inputobject } More on reddit.com
🌐 r/PowerShell
29
5
December 4, 2017
How to iterate through an array of objects in Powershell - Stack Overflow
I'm doing some basic validation on form fields. What's the correct way to iterate through an array of objects to validate them? When I try the below I get The property 'BackColor' cannot be found on More on stackoverflow.com
🌐 stackoverflow.com
Update scripts to use arraylist instead of array in foreach loops ?
You've misunderstood this. Assigning results from a loop like you do here is the ideal way to add objects to a collection. When you are doing this, Powershell will internally add objects to a list or an arraylist (not sure which) and finally convert that to an array. It's also worth noting that arraylists are better than arrays when adding items 1 by 1 but lists are even better. There's never a reason to use arraylists over lists so just don't even think about them. More on reddit.com
🌐 r/PowerShell
21
1
August 31, 2021
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › how to loop through an array in powershell?
How to Loop through an Array in PowerShell? - SharePoint Diary
October 21, 2025 - # Loop through an array of strings $colors = @("Red", "Green", "Blue") foreach ($color in $colors) { Write-Host $color } The following example shows how you can iterate through ArrayList in PowerShell script:
🌐
Microsoft
devblogs.microsoft.com › dev blogs › scripting blog [archived] › basics of powershell looping: foreach
Basics of PowerShell Looping: Foreach - Scripting Blog [archived]
April 28, 2014 - In Windows PowerShell, if I add 5 to my $d variable, I end up actually adding the value as another element in the array. This is shown here: ... To add the number five to each of the elements in the array, I need to walk through the array by using the Foreach command.
🌐
Adam the Automator
adamtheautomator.com › powershell-array
PowerShell Arrays, ArrayLists & Collections: Best Practices
PS51> $MyArray = @() PS51> $MyArrayList = [System.Collections.ArrayList]@() Next, populate 50,000 elements in each collection using the range operator and a foreach loop as shown below.
Published   April 22, 2025
🌐
Lexdsolutions
lexdsolutions.com › post › 2022-10-23-supercharge-powershell-using-foreach-and-arraylist
Supercharge PowerShell using ForEach and ArrayList • Lexd Solutions
October 23, 2022 - By default, when we set a variable using @() in PowerShell, this will create us an Array object. Example: PS C:\> $myVar = @() PS C:\> $myVar.GetType() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Object[] System.Array · Since arrays are fixed length, each time we perform a ”+=” action, a new array needs to be created with that new additional element. ArrayList does not have a fixed length so new elements can be added into the list with minimal overhead.
🌐
SPGuides
spguides.com › powershell-loop-through-array
How to Loop Through an Array in PowerShell?
March 26, 2025 - Another powerful technique for looping through an array in PowerShell is by using the pipeline with the ForEach-Object cmdlet. The pipeline allows you to pass the array elements to the ForEach-Object cmdlet, which then executes a script block ...
🌐
Reddit
reddit.com › r/powershell › how to update an arraylist inside a foreach -parallel
r/PowerShell on Reddit: How to update an arraylist inside a foreach -parallel
May 17, 2023 -

I can't update the arraylist. When I try to add an object to the array list, i get the following error: "You cannnot call a method on a null-valued expression."

Can anyone offer advice?

My code:

$OpenFiles = Get-SmbOpenFile
$FSShares = Get-SMBShare | where {$_.ScopeName -ne '*'}
$Alldata = [System.Collections.ArrayList]@()

$OPenFiles | foreach-object -parallel {
    $UserAccount = $psitem.ClientUserName
    $FullPath = $psitem.Path
    $RPath =   $psitem.ShareRelativePath
    $SourceIP = $psitem.ClientComputerName
    $RootShare = $fullpath.Replace("\$rpath","")

    $ShareInfo = $FSShares | where {$_.Path -like $RootShare}
    $Sharename = $ShareInfo.Name
    $FSRole = $ShareInfo.ScopeName

    $obj = new-object psobject
    $obj | Add-Member -MemberType NoteProperty -Name 'Role' -Value $FSRole
    $obj | Add-Member -MemberType NoteProperty -Name 'ShareName' -Value $ShareName
    $obj | Add-Member -MemberType NoteProperty -Name 'PathToShare' -Value $RootShare
    $obj | Add-Member -MemberType NoteProperty -Name 'Account' -Value $UserAccount
    #$obj | Add-Member -MemberType NoteProperty -Name 'ShareName' -Value $ShareName
 
    $Alldata.Add($Obj) | out-null

}
Find elsewhere
🌐
Reddit
reddit.com › r/powershell › loop with foreach removing from arraylist.
r/PowerShell on Reddit: Loop with foreach removing from arraylist.
December 4, 2017 -

Hello :)

Was wondering if any of you kind gentlemen/women could help me understand whats wrong with a small script im writing.

https://pastebin.com/rDNacxqb

Getting error: WARNING: ZLE0294: Exception calling "Find" with "2" argument(s): "Unspecified error"

Edit:

What i ended up running:

$Laptops = ((Get-ADComputer -Filter {Name -like "COMP*"}).name)
$Logfile = "C:\Temp\EXPORT\LocalAdminZLE $(get-date -f yyyy-MM-dd).csv"

while ($Laptops){

    foreach ($laptop in $laptops){

        if (Test-Connection -Computername $Laptop -BufferSize 16 -Count 1 -Quiet){
            
            $C = Get-LocalGroup -Computername $laptop -Group Administrators
            if($C){

                $C | Export-Csv $Logfile -Append
                $laptops = $laptops -ne $laptop
            }

        }
    }

}

Seems to be working so far.

Top answer
1 of 5
3
I think this should fix your problem $Laptops = ((Get-ADComputer -Filter {Name -like "COMP*"}).name) $TempTops = @() $Logfile = "C:\Temp\EXPORT\LocalAdminZLE $(get-date -f yyyy-MM-dd).csv" while ($Laptops) { foreach ($laptop in $laptops) { $C = Get-LocalGroup -Computername $laptop -Group Administrators if($C) { $C | Export-Csv $Logfile -Append $TempTops += $laptop } $C = $null } $Laptops = Compare-Object $Laptops $TempTops | where {$_.sideindicator -eq "<="} | select -ExpandProperty inputobject }
2 of 5
3
So you are mixing and matching Arrays and ArrayLists. If you are going to go to the trouble of using ArrayLists, instead of using: $Laptops = $Laptops | Where-Object { $ToRemove -notcontains $_ } You should just do $Laptops.Remove($laptop) Unfortunately, that doesn't really work in the foreach loop, because you're going to break enumeration. So I'm not sure if this is a good solution, but it is what I would do - the only reason I'm hesitant is because it was recently suggested the a "for" loop is a PowerSmell (indication of bad coding), but this is how I get around this type of issue: for ( $i=0; $i -lt $Laptops.count; $i++ ) { $C = Get-LocalGroup -Computername $Laptops[0] -Group Administrators if($C){ $C | Export-Csv $Logfile -Append # [void]$Laptops.Remove($Laptops[0]) } [void]$Laptops.Remove($Laptops[0]) } I'm not sure what u/markekraus would do differently, but that is how I would handle it. edit: Just noticed an issue with this - we aren't always removing the laptop from the arraylist, so laptops[0] will not always get dropped out, and you would get an infinite loop if $c is null. So move that outside the if statement (code updated).
🌐
GitHub
github.com › PowerShell › PowerShell › discussions › 16082
ForEach array not collecting correctly · PowerShell/PowerShell · Discussion #16082
I ran this on a machine that had not been updated to Powershell 7, and the array collections worked fine. [system.collections.arraylist]$Onlinecomputers=@() [system.collections.arraylist]$Offlinecomputers=@() ForEach ($server in $servers) { if (Test-Connection -ComputerName $server -Count 1 -Quiet) { Write-Host $server is online $onlinecomputers += $server } Else { Write-Host $server is offline $offlinecomputers += $server } } Beta Was this translation helpful?
Author   PowerShell
🌐
Saved Keystrokes
savedkeystrokes.github.io › powershell › 2017 › 09 › 15 › array-foreach.html
PowerShell: $array.ForEach({}) | Saved Keystrokes
September 15, 2017 - Most times, when you think about writing something in PowerShell, you will usually find within the first lines a Get-ChildItem, you will then inevitably have a for each loop. Normally I would write this as foreach($item in $items), but on one occasion the autocomplete came up on the array variable ...
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › how to use foreach loop with arrays in powershell?
How to Use ForEach Loop with Arrays in PowerShell? - SharePoint Diary
October 25, 2023 - If each iteration involves network calls or disk operations, ForEach-Object -Parallel in PowerShell 7 can cut total execution time dramatically. Here is a quick comparison of appending items to see the performance difference: ... # Slow - creates a new array every iteration $results = @() foreach ($item in 1..10000) { $results += $item } # Fast - ArrayList grows dynamically $results = [System.Collections.ArrayList]@() foreach ($item in 1..10000) { $results.Add($item) | Out-Null }
🌐
Brianbunke
brianbunke.com › blog › 2018 › 01 › 04 › powershell-arraylist
PowerShell ArrayList Module - Brian Bunke
January 4, 2018 - UPDATE 2018/01/13: v1.1.0 released to almost exclusively use Generic.List instead of ArrayList. Details below · You need to capture output within a ForEach loop in your PowerShell code. How do you do it quickly?
🌐
Reddit
reddit.com › r/powershell › update scripts to use arraylist instead of array in foreach loops ?
r/PowerShell on Reddit: Update scripts to use arraylist instead of array in foreach loops ?
August 31, 2021 -

I'm struggling to wrap my head around this one, but I understand that arraylists have less overhead than arrays do when creating them. I'd like to update some of my scripts to output results to arraylists instead of arrays.

Example of my current setup which outputs an array object

$results = foreach($computer in $list){
    if($computer.name -like "*Finance*"){
        [pscustomobject]@{
            Department = "Finance"
            Computer = $computer.name
        }
    }
    elseif($computer.name -like "*Marketing*"){
        [pscustomobject]@{
            Department = "Marketing"
            Computer = $computer.name
        }
    }
}

$results

Department     Computer
______         _____
Finance        Finance01comp
Marketing      Marketing01comp

From what I gather, this will rewrite the entire array every time I loop through $list. Is there a way to just have each loop append an arraylist with consistent property names but different property values? (assume my $list is much larger than 2 computers lol)

🌐
SS64
ss64.com › ps › foreach.html
The ForEach PowerShell statement
Syntax ForEach [-Parallel] (item In collection) {ScriptBlock} key item A variable to hold the current item collection A collection of objects e.g. filenames, registry keys, servernames ScriptBlock A block of script to run against each object. -Parallel Run the commands once for each item in parallel (PowerShell Workflow only).
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › powershell tutorials › powershell foreach-object loop: beginner’s guide
PowerShell ForEach-Object Loop: Beginner's Guide - SharePoint Diary
September 30, 2025 - Learn how to use the ForEach loop and the ForEach-Object cmdlet to traverse all the items in a collection in PowerShell scripts with this guide!
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_foreach
about_Foreach - PowerShell | Microsoft Learn
January 19, 2026 - In this example, the $letterArray contains the string values a, b, c, and d. The first time the foreach statement runs, it sets the $letter variable equal to the first item in $letterArray (a). Then, it uses Write-Host to display the value. The next time through the loop, $letter is set to b.