
Like other programming languages, arrays provide a simple way to store a list of items in PowerShell. However, standard PowerShell arrays have limitations – they are fixed-sized and don’t provide many helpful methods to manipulate the array contents. This is where ArrayLists come in. The ArrayList is one of the most useful collection types in PowerShell. It provides a dynamic array that can grow and shrink as needed. ArrayLists make it easy to add, remove, sort, and update items in the collection.
In this post, you will learn how to:
- Create ArrayLists in PowerShell
- Add, insert, and remove items from an ArrayList
- Resize ArrayLists dynamically
- Sort and reverse ArrayLists
- Access items by index
- Concatenate multiple ArrayLists
- Convert between ArrayList and arrays
- Search for items in an ArrayList
In this comprehensive guide, we will delve into the depths of the PowerShell ArrayList, from creation to manipulation, uncovering its features and benefits, troubleshooting common errors, and sharing tips to optimize your script performance.
You can do crazy things in PowerShell, one of which is to get file names only. In this article, I will show you how to list file names only in PowerShell.
To list file names only in PowerShell, you can use the Get-ChildItem cmdlet combined with the -Name parameter. For example, Get-ChildItem -Path “C:\Your\Directory” -Name outputs all the file names in the specified directory. To exclude directories and list only files, append the -File parameter, like so: Get-ChildItem -Path “C:\Your\Directory” -File -Name.
Get File Names Only Using Get-ChildItem Cmdlet
Let us try the most simplest approach.
The primary command for listing files in PowerShell is Get-ChildItem. This cmdlet retrieves the items and child items in one or more specified locations. To list file names only, you can use this cmdlet in its simplest form.
Get-ChildItem -Path "C:\MyFolder" -NameThe -Path parameter specifies the directory, and the -Name parameter ensures that only the names of the files are displayed, excluding other details like size, type, or modification date.
You can see in the screenshot below that I executed the script using VS code.

Filter Out Directories
By default, Get-ChildItem lists both files and directories in PowerShell. If you want to list only files, you can filter out the directories using the -File parameter.
Get-ChildItem -Path "C:\MyFolder" -File -NameThis command will return a list of file names without their extensions, and it will ignore only the folder names.
Get File Names Excluding File Extensions
If you want to list the files but exclude their extensions, you can use a combination of Get-ChildItem and ForEach-Object cmdlets in PowerShell.
Get-ChildItem -Path "C:\MyFolder" -File | ForEach-Object { $_.BaseName }This script lists the base names (file names without extensions) of all the files in the specified directory.

Get File Names Only Recursively
To list files in the specified directory and all subdirectories, use the -Recurse parameter in the PowerShell Get-ChildItem cmdlets.
Get-ChildItem -Path "C:\MyFolder" -Recurse -File -NameThis command will list all file names, including those in all levels of subdirectories under the target directory.
Advanced Filtering with Where-Object
Here is the complete PowerShell script.
Get-ChildItem -Path "C:\MyFolder" -File | Where-Object { $_.Name -like '*myfile*' } | ForEach-Object { $_.Name }Conclusion
The simplest way you can use the Get-ChildItem PowerShell Cmdlet.
Microsoft 365 distribution lists are a handy way to send emails to a large group of people. But over time, projects end, teams restructure, and employees move on. What happens to the corresponding distribution lists (DL)? If these distribution lists remain untouched, they become inactive. They clog up your directory, potentially posing security risks and hindering overall email efficiency. But, how to determine if a distribution group is being used or not?
Message Trace Report in Exchange Online?
Message trace reports in Exchange Online track email usage, including when emails are sent or received by mailboxes. This helps to identify which distribution lists are actively used and which ones are inactive within a defined period (usually up to 90 days).
- Sign in to the
- Navigate to Mail flow –> Message Trace –> Start a trace.
- Then, specify the timeframe for the trace (up to 90 days) or set a custom start date and end date.
- Once you’ve set the time range, click

The search will run, and the results won’t be available immediately. You can check the status under the tab. When the report is ready, you can download it in CSV format.
$endDate = (Get-Date).Date $startDate = $endDate.AddDays(-90) |

After downloading the message trace report, we can proceed with executing the script to identify unused distribution groups!
Download Script: FindInactiveDistributionLists.ps1
- The script automatically verifies and installs the Exchange PowerShell module (if not installed already) upon your confirmation.
- inactive days of distribution lists in Microsoft 365.
- last email received date
- Exports report results to
- The script is
- It can be executed with certificate-based authentication (CBA)
- Last Email Received Date
The exported report will look similar to the screenshot below:

Microsoft 365 Inactive Distribution Lists Report – Script Execution Methods
- Download the script.
- Start the Windows PowerShell.
- Select any of the methods provided to execute the script.
Export Inactive Distribution Lists into CSV
You can run the script with MFA and non-MFA accounts.
./FindInactiveDistributionLists.ps1 – HistoricalMessageTraceReportPath “./MessageTraceReport.csv” |
specifies the path to the CSV file containing the message trace report.
This example allows you to find the last date a distribution list was used, thereby finding all the inactive DLs in the organization.
You can also verify distribution group members to access their future requirements and plan to remove inactive DLs.
Group Usage Report
You can also run the script using certificate-based authentication, which is scheduler friendly. When you want to run the script unattended, you can choose this method. Exchange Online using a certificate, you must register the app in Azure AD
./FindInactiveDistributionLists.ps1 – HistoricalMessageTraceReportPath “./MessageTraceReport.csv” -Organization <Domain> -ClientID <AppId> -CertificateThumbPrint <CertThumbPrint> |
For the most accurate results in identifying distribution groups usage, it’s recommended to schedule the script to run to 90 days once. Make sure to update the message trace report manually before the scheduled date. Alternatively, you can schedule the trace report to automatically to store in the specific location.
This helps you gather and analyze data over a longer period for a better understanding of distribution list activity.
Schedule Inactive Distribution Lists in Microsoft 365
Access and Retrieve Elements
To get the number of elements in ArrayList:
To retrieve an element by index:
$item1 = $Arraylist[0] $item2 = $Arraylist[1]
You can access elements just like a standard PowerShell array.
To retrieve the last element:
$LastItem = $ArrayList[-1]
Loop Through ArrayList with Foreach
To process all elements in ArrayList, use Foreach:
ForEach ($Element in $ArrayList) { # Do something with $Element Write-Output $Element
}This iterates through each element sequentially. You can also use a for loop with Count:
For($i=0; $i -lt $Arraylist.Count; $i++) { # Do something with $element $element = $arraylist[$i] Write-host $Element
}Here is another form:
$ArrayList | ForEach-Object { Write-Host $_
}Common errors and troubleshooting in PowerShell ArrayList
As you work with PowerShell ArrayList, you may encounter some common errors or issues. In this section, we will discuss some of these errors and provide tips for troubleshooting and resolving them.
- Index out of range: This error occurs when you try to access or modify an element at an index that does not exist in the ArrayList. To avoid this error, always ensure that the index you are using is within the bounds of the ArrayList. You can use the
Countproperty to get the number of elements in the ArrayList. - InvalidCastException: This error occurs when you try to convert an element in the ArrayList to an incompatible data type. To fix this error, ensure that you are using the correct data type for the element in question or use the appropriate conversion methods provided by PowerShell and the .NET Framework.
- Adding elements of different data types: While it is possible to store elements of different data types in an ArrayList, doing so can lead to unexpected behavior and performance issues. To avoid this, try to use a consistent data type for all elements in the ArrayList or consider using a different collection type, such as a Hashtable or a custom object.
Export ArrayList to CSV
Let’s say you have an ArrayList like this:
$ArrayList = New-Object System.Collections.ArrayList
$ArrayList.Add("Apple")
$ArrayList.Add("Banana")
$ArrayList.Add("Cherry")The challenge here is that this ArrayList contains simple string data, and Export-Csv expects objects with properties. To resolve this, you could create a custom object array from these simple data types, like:
#Convert ArrayList to Object array
$Objects = $ArrayList | ForEach-Object { [PSCustomObject]@{Fruit = $_} }
#Export Array to CSV
$Objects | Export-Csv -Path "C:\Temp\Fruits.csv" -NoTypeInformationCreating an ArrayList in PowerShell
$arrayList = New-Object -TypeName System.Collections.ArrayList
This initializes an empty ArrayList. Alternatively, you can use type accelerators to create a new array list variable:
$ArrayList = [System.Collections.ArrayList]::new()
Initialize ArrayList with a capacity: When creating an ArrayList, it’s a good idea to initialize it with a capacity close to the expected number of elements. This can help reduce the number of memory allocations and improve the performance of your script. For example, if you expect your ArrayList to have approximately 100 elements, you can create it like this:
$ArrayList = New-Object -TypeName System.Collections.ArrayList -ArgumentList 100
$ArrayList = [System.Collections.ArrayList]@("Banana", "Cherry", "Apple","Orange")Both methods will create a new ArrayList object, which you can then use to store and manipulate data in your PowerShell script.

Unlike the default array, the ArrayList can contain a mix of data types. E.g., let’s say you want to create an “Employee” ArrayList with Employee Number, Employee Name, and Date of Join values:
$Employee = New-Object System.Collections.ArrayList
$Employee.Add(001)
$Employee.Add("Steve Johnson")
$Employee.Add([DateTime]"01/01/2021")PowerShell Import CSV to ArrayList
You can import a CSV file into an ArrayList using Import-Csv and a ForEach loop.
$csvData = Import-Csv -Path 'C:\Temp\Fruits.csv'
$ArrayList = New-Object System.Collections.ArrayList
ForEach ($row in $csvData) { $ArrayList.Add($row)
}Adding elements to PowerShell ArrayList
Once your ArrayList is created, Adding elements to a PowerShell ArrayList is easy, with the help of the built-in Add() method. This method allows you to add a single element to the end of the ArrayList:
Alternatively, you can use the AddRange() method to ArrayList with a set of initial values.
$Fruits = @("Banana", "Cherry", "Date")
$ArrayList.AddRange($Fruits)$initialValues = 1..5 $arrayList = New-Object -TypeName System.Collections.ArrayList $arrayList.AddRange($initialValues)
Here is another way to add multiple elements to an array list with the help of a Loop:
#Create a Array List
$ArrayList = New-Object System.Collections.ArrayList
#Add Elements to Array List
@(0..100).ForEach({$ArrayList.Add($_)})Additionally, the Insert() method can be used to insert an element at a specific index within the ArrayList:
$arrayList.Insert(0, "Plums")
This code will insert “Plums” at the beginning of the ArrayList (index 0). Keep in mind that the index is zero-based, meaning that the first element has an index of 0, the second element has an index of 1, and so on.
You can use the GetType() method to retrieve the data type of an element stored in the ArrayList. E.g.,
$ArrayList[0].GetType().Name
Convert Between ArrayList and Arrays
You can easily convert between ArrayList and standard PowerShell arrays:
Convert ArrayList to array
To convert an ArrayList to an array, use the typecasting as:
$Array = [array]$ArrayList
You can also use the ToArray() method:
$array = $arraylist.ToArray()
How about the reverse? To convert an existing array to ArrayList, use:
$arraylist = [System.Collections.ArrayList]$array
The array or ArrayList gets cast to the target type automatically.
Understanding ArrayList and its Benefits in PowerShell

Understanding how to work with ArrayLists unlocks more flexible scripting capabilities. The ArrayList is a generic List collection type found in the System.Collections.ArrayList class. You can store ordered collections of any object type, like strings, numbers, custom objects, etc. Unlike the traditional PowerShell array, ArrayList can grow and shrink dynamically, making it ideal for situations where the number of elements is not known in advance or needs to change over time.
The benefits of using an ArrayList in PowerShell are numerous:
- Dynamic size: As mentioned earlier, ArrayList can grow and shrink dynamically, unlike the traditional array in PowerShell. This means you can easily add or remove elements without worrying about resizing the array or losing data.
- Improved performance: ArrayList provides better performance compared to the traditional array, especially when dealing with large volumes of data. This is because ArrayList uses a more efficient method of storing and retrieving data, which reduces the time and resources required to process your scripts.
- Compatibility: ArrayList is compatible with other PowerShell objects and can be easily converted to different data types, such as strings or arrays. This makes it a versatile choice for working with various data sources and formats.
- Rich built-in methods: ArrayList provides several built-in methods for manipulating and processing data. These methods include adding elements, removing elements, sorting, and searching, among others.
PowerShell ArrayList vs. Array: Key differences
- ArrayList is a dynamic collection of objects that can grow and shrink dynamically, while Array is a static collection of objects with a fixed size. This means that once an Array is created, its size cannot be changed.
- ArrayList provides better performance compared to Array when dealing with large volumes of data or when the number of elements is not known in advance. This is because ArrayList uses a more efficient method of storing and retrieving data, which reduces the time and resources required to process your scripts.
- PowerShell Arrays are strongly typed (meaning they can only store elements of a specific type). In contrast, ArrayLists can store values of any data type.
- On the other hand, Array offers better performance when dealing with a small number of elements or when the size of the collection is fixed. This is because Array uses a more straightforward method of storing and retrieving data, which can be faster than ArrayList in some cases.
When choosing between PowerShell Array List and Array, consider the size and nature of your data, as well as the performance requirements of your script. Here is another post on using arrays in PowerShell: How to use Arrays in PowerShell?
Modifying ArrayList elements in PowerShell
Once you have an ArrayList in your PowerShell script, there are several methods available to manipulate and modify its elements. To change the value of an element in an ArrayList, you can use the set_Item() method or the array index notation. For example, to update the first element, you can use:
$ArrayList.set_Item(0, "Updated Element") #Another way $ArrayList[0] = "Updated Element".
We will explore more advanced manipulation techniques, such as sorting, reversing, and searching, in a later section of this article.
- Inactive Distribution Groups by Mails Received
- Inactive distribution Groups by External Mails Received
- Daily Top Distribution Groups by Mails Sent/Received
- Top DLs based on Sending/Receiving Internal Emails
- Top DLs based on Sending/Receiving External Emails
- Active Distribution Groups by Mail Sending/Receiving Frequency
- Monthly/Hourly/Daily Distribution Groups Mail Traffic Stats
- All Distribution Groups
- Distribution Group Members
- Distribution Group Membership Changes

I hope this blog will help you find out inactive distribution lists in your organization. If you have any queries, reach us through the comment section.
Real-world applications of PowerShell ArrayList
PowerShell ArrayList can be used in a variety of real-world scenarios, such as:
- Log file processing: ArrayList can be used to store and process log file data, allowing you to filter, sort, and analyze log entries efficiently.
- Inventory management: PowerShell ArrayList can be utilized to store and manage inventory data, such as computer names, IP addresses, and hardware details.
- Data processing: ArrayList can be employed in data processing tasks, such as parsing CSV files, processing XML data, or handling JSON objects.
- Script optimization: As mentioned earlier, using ArrayList can help improve the performance of your PowerShell scripts, making it a valuable tool for script optimization tasks.
- Storing ordered collections like lists of servers, users, etc., that change frequently
- Collecting output from loops and pipelines before exporting to CSV
Removing elements from a PowerShell ArrayList
Removing elements from a PowerShell ArrayList is a common operation that can be done using the Remove(), RemoveRange() or RemoveAt() methods. Whether you want to remove a specific element, or multiple elements, or even clear the entire list, there’s a method to help you do just that. Here’s how:
The Remove() method removes the first occurrence of a specified element, while the RemoveAt() method removes the element at a specific index.
$arrayList.Remove("apple")Removing a Range of Elements
The RemoveRange method allows you to remove a range of elements by specifying the starting index and the number of elements to remove parameters:
$ArrayList.RemoveRange(0,2) # This will remove the first two elements
To remove all items from the ArrayList, use the Clear() method:
Clear() empties the entire ArrayList.
Keep in mind that these methods modify the original Array List object, so use them with caution and ensure that you are removing the correct elements.
Converting PowerShell ArrayList to string
$string = $arrayList -join ', '
Or, using the String.Join() method:
$string = [System.String]::Join(', ', $arrayList)Both methods will create a new string containing the elements of the ArrayList, separated by the specified delimiter (a comma and a space in this case).
Join Multiple ArrayLists
To combine multiple ArrayLists:
$arraylist1 = [System.Collections.ArrayList]@(1, 2, 3) $arraylist2 = [System.Collections.ArrayList]@(4, 5, 6) $result = $arraylist1.Clone() $result.AddRange($arraylist2)
Clone() makes a copy before appending $arraylist2 to avoid modifying the original.
Filter ArrayList
You can filter elements in ArrayList using the Where method:
#Create a Array List with values: 1 to 10
$Values = 1..10
$ArrayList = New-Object -TypeName System.Collections.ArrayList
$ArrayList.AddRange($Values)
#Filter Array List
$Arraylist = $ArrayList.Where{$_ -ge 5}Alternatively, You can use the Where-Object cmdlet to Filter Array elements:
#Filter ArrayList
$MyArraylist = $ArrayList | Where-Object {$_ -ge 5}Sorting, reversing, and searching PowerShell ArrayLists
PowerShell ArrayList provides several methods for manipulating and processing data, such as sorting, reversing, and searching.
$ArrayList.Sort() $ArrayList.Reverse()
This code will first sort the ArrayList in ascending order and then reverse the order to get the elements in descending order. The Sort-Object cmdlet also can be used for sorting elements in the array:
$SortedArrayList = $ArrayList | Sort-Object

if ($ArrayList.Contains("apple")) { Write-Host "ArrayList contains 'apple'"
}This code will check if the ArrayList contains the element “apple” and print a message if it does.
Conclusion
ArrayLists provide a powerful alternative to standard PowerShell arrays for storing dynamic collections. In this comprehensive guide, we have covered the essentials of PowerShell ArrayList, from creation and manipulation to troubleshooting common errors of this fantastic data structure. We have also explored real-world use cases and provided tips for optimizing script performance. By understanding the features and benefits of ArrayList, you can easily store and manipulate data in a dynamic and efficient way.



