Skip to content

Automatic variable for the pipeline index #13772

@iRon7

Description

@iRon7

Summary of the new feature/enhancement

Initiate and increase an automatic variable (e.g. $PSIndex) each time the current object ($_/$PSItem) is assigned to the next object.

The thought originated from request #13769; what if there isn't a parameter available to support my index selection requirement?
E.g.: in case I want to get each odd row to reformat it for a readability (or a combination with #13769 or anything else)
I would need to create a custom index. That index needs to be initiated and increased with each iteration, something like:

$Index = 0
'A'..'E' | Where-Object { $Index++ -notin 1, 3 }

This is also required in a other situations, as shown in StackOverflow questions along with:

See also: Get index of current item in a PowerShell loop

Examples

If there would be an automated index variable, these solutions could be simplified to:

#13769 NotIndex

'A'..'E' | Where-Object { $PSIndex -notin 1, 3 }

Select odd rows

'A'..'E' | Where-Object { $PSIndex % 2 }

Combine single arrays into columns

$Column1 = 1..3
$Column2 = 4..6

$Column1 | Foreach-Object {
    [pscustomobject]@{ Column1 = $_; Column2 = $Column2[$PSIndex] }
}

Make array elements as the keys of hashtable

$Keys = 1,2,3
$Values = 'One', 'Two', 'Three'

$HashTable = @{}
$Keys | Foreach-Object { $HashTable[$_] = $Values[$PSIndex] }

Fundamental test (expectation)

$Collection | Foreach-Object {
    $Collection[$PSIndex].Equals($PSItem) | Should -BeTrue
}

Caveats

  • I suspect that there already internally exists an index to support parameters like -Index and -Skip in the Select-Object cmdlet but I have no clue if that is available for every cmdlet in the pipeline
  • The automatic index variable for every cmdlet in the pipeline (and methods like .Where{ $PSIndex ... } ?) should all refer to a different index: 1..5 | % { $PSIndex } | ... | { $PSIndex } (as also the case with $_/$PSItem)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Enhancementthe issue is more of a feature request than a bugKeepOpenThe bot will ignore these and not auto-closeWG-Enginecore PowerShell engine, interpreter, and runtimeWG-NeedsReviewNeeds a review by the labeled Working Group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions