Select-Nth.psm1

function Select-Nth {
    <#
    .SYNOPSIS
    Retrieves or skips every Nth object from the input collection.
 
    .DESCRIPTION
    This function filters the input collection and returns, or skips, every Nth object.
 
    .PARAMETER InputObject
    The collection of objects to filter.
 
    .PARAMETER Nth
    The interval for selecting objects (e.g., return every 5th object).
 
    .PARAMETER SkipNth
    The interval for skipping objects (e.g., skip every 5th object).
 
    .EXAMPLE
    Select-Nth -InputObject $myObjects -Nth 3
 
    .EXAMPLE
    1..10 | Select-Nth -Nth 2
 
    .EXAMPLE
    1..10 | Select-Nth -SkipNth 3
    #>



    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline, Mandatory, ParameterSetName = 'nth')]
        [Parameter(ValueFromPipeline, Mandatory, ParameterSetName = 'skip_nth')]
        [Object[]]
        $InputObject,

        [Parameter(Mandatory, ParameterSetName = 'nth')]
        [int]$Nth,

        [Parameter(Mandatory, ParameterSetName = 'skip_nth')]
        [int]$SkipNth
    )

    begin {

        $object_counter = 0;
    }


    process {
        $InputObject | ForEach-Object {
            $object_counter++;

            if ($PSCmdlet.ParameterSetName -eq 'skip_nth') {
                if ($object_counter -ge $SkipNth) {
                    $object_counter = 0;
                }
                else {
                    Write-Output $InputObject
                }
            } 

            if ($PSCmdlet.ParameterSetName -eq 'nth') {
                if ($object_counter -ge $Nth) {
                    Write-Output $InputObject
                    $object_counter = 0;
                }
            }

        }

    }


}