Samples/PagingHelperEarlyExit.ps1

# This script demonstrates how to efficiently find a single, specific item from a paged API endpoint.
# It uses a pipeline with an "early exit" to stop processing as soon as the item is found,
# preventing unnecessary API calls to fetch remaining pages.

# Sets Write-Information for console output and ensures the script stops on errors.
# PowerShell default is SilentlyContinue
$InformationPreference = "Continue"
$ErrorActionPreference = "Stop"

# --- Configuration ---
# The name of the specific endpoint you want to find.
$mySpecificEndpointName = "YourEndpointName1"

try {
    # This pipeline demonstrates finding an item and exiting early:
    # 1. Get-bCEndpointsWindowsEndpoints -GetAllPages: Starts fetching pages of endpoints.
    # 2. Select-bCPageData: Extracts the items from each page as it is retrieved.
    # 3. Where-Object: Filters the items, looking for a match by displayName.
    # 4. Select-Object -First 1: This is the key for early exit. As soon as one item matches the Where-Object filter,
    # Select-Object takes that item and terminates the pipeline. No more pages will be fetched.
    # Note: This example fetches all pages until the item is found, which is very slow for large datasets.
    # Use more specific filters in the initial API call if possible.
    Write-Information "Searching for endpoint '$mySpecificEndpointName' with early exit..."
    $specificEndpoint = Get-bCEndpointsWindowsEndpoints -GetAllPages `
                                | Select-bCPageData `
                                | Where-Object {
                                    Write-Information "Processing Endpoint $($_.displayName)"
                                    return $_.displayName -eq $mySpecificEndpointName
                                } `
                                | Select-Object -First 1 # Exits the pipeline after finding the first match

    if ($specificEndpoint) {
        Write-Output "Found Endpoint: $($specificEndpoint.displayName) (ID: $($specificEndpoint.id))"
    }
    else {
        Write-Warning "Endpoint '$mySpecificEndpointName' not found."
    }
}
catch {
    Write-Error "An error occurred: $($_.Exception.Message):`n$($_.ScriptStackTrace)"
}