24/7/365 Support

Access Pipeline Input in Windows PowerShell

Problem

You want to interact with input that a user sends to your function, script, or script block via the pipeline.

Solution

To access pipeline input, use the $input variable as shown by Example 107.

Example 107. Accessing pipeline input

function InputCounter {

$count = 0

## Go through each element in the pipeline, and add up

## how many elements there were.

foreach($element in $input)

{

$count++

}

$count }

which produces the following (or similar) output when run against your Windows system directory:

PS >dir $env:WINDIR | InputCounter

295

Discussion

In your scripts, functions, and script blocks, the $input variable represents an enumerator (as opposed to a simple array) for the pipeline input the user provides. An enumerator lets you use a foreach statement to efficiently scan over the elements of the input (as shown in Example 107) but does not let you directly access specific items (such as the fifth element in the input, for example).

An enumerator only lets you to scan forward through its contents. Once you access an element, PowerShell automatically moves on to the next one. If you need to access an item that you’ve already

accessed before, you must call $input.Reset() to scan through the list again from the beginning, or store the input in an array.

If you need to access specific elements in the input (or access items multiple times), the best approach is to store the input in an array. This prevents your script from

taking advantage of the $input enumerator's streaming behavior, but is sometimes the only alternative. To store the input in an array, use PowerShell’s list evaluation syntax ( @() ) to force PowerShell to interpret it as an array.

function ReverseInput

{

$inputArray = @($input)

$inputEnd = $inputArray.Count 1

$inputArray[$inputEnd..0] }

which produces

PS >1,2,3,4 | ReverseInput 4 3 2 1

If dealing with pipeline input plays a major role in your script, function, or script block, PowerShell provides an alternative means of dealing with pipeline input that may make your script easier to write and understand. 

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say