Public/Get-ComputerListByFilter.ps1

<#
    .SYNOPSIS
    Retrieves a list of computer names from Active Directory that match a specific filter.
     
    .DESCRIPTION
    This function searches the Active Directory for computers by a specific name pattern.
    It is designed to handle large datasets efficiently by using pagination.
     
    .PARAMETER DN
    The distinguished name (DN) of the Active Directory domain or OU to search within.
     
    .PARAMETER FilterName
    The name filter for computer objects. Defaults to all names containing 'AFS'.
     
    .EXAMPLE
    Get-ComputerListByFilter -DN "OU=Computers,DC=example,DC=com" -FilterName "*AFS*"
    Retrieves all computers whose names contain 'AFS' in the specified OU.
     
    .EXAMPLE
    "OU=Computers,DC=example,DC=com" | Get-ComputerListByFilter -FilterName "*Server*"
    Pipe a DN string and retrieve computers with 'Server' in their names.
 
    .NOTES
     Requires administrative privileges on the remote computer and appropriate permissions to use PowerShell remoting.
#>

Function Get-ComputerListByFilter {

    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$DN,

        [Parameter(Mandatory = $false, ValueFromPipeline = $true)]
        [string]$FilterName = "*AFS*"
    )

    process {
        try {
            $OU = "LDAP://$DN"
            $searcher = New-Object DirectoryServices.DirectorySearcher([ADSI]$OU)
            $searcher.PageSize = 1000  # Enables efficient processing of large datasets by fetching pages of results.

            # Building the filter with the provided name pattern
            $searcher.Filter = "(&(objectCategory=computer)(name=$FilterName))"

            # Optimize the search by loading only the required properties
            $searcher.PropertiesToLoad.Add("name") > $null

            # Retrieving and outputting the names of the matching computers
            foreach ($result in $searcher.FindAll()) {
                $result.Properties["name"][0]
            }
        } catch {
            Write-Error "Failed to search in AD: $_"
        }
    }
    end {
        # Any necessary cleanup can be performed here, though DirectorySearcher does not require manual disposal
    }
}