Pipeline input is data supplied to a PowerShell command by a preceding pipeline command. Designing functions to accept it lets commands work independently or as reusable stages in larger automation tasks. section 4.5 section 17.1.3
A function accepts pipeline input through parameter-binding attributes and processes objects in pipeline-aware stages:
- Use ValueFromPipeline for ByValue binding. A string parameter such as $ComputerName can receive each incoming string object. section 11.1.1
- Use ValueFromPipelineByPropertyName when incoming objects are not strings but expose a matching property, such as ComputerName. section 11.1.1
- Put per-object work in PROCESS{}. PowerShell runs it as each pipeline value is bound, then runs END{} after all objects have passed through. section 11.1.1
- Design the function for both direct parameter use and pipeline use; the extra parameter and processing structure prevent a tool from being locked to one calling style. section 11.1.1 section 27.2
Passing computer names through a function
Direct invocation supplies multiple values as a parameter: Get-MachineInfo -ComputerName ONE,TWO,THREE. Pipeline invocation supplies them one at a time: "ONE","TWO","THREE" | Get-MachineInfo. With [Parameter(ValueFromPipeline=$True)] on $ComputerName, PROCESS{} runs for each computer, while END{} can perform final work such as writing "All Done". section 11.1.1
Listing 11.1 Original Get-MachineInfo function
function Get-MachineInfo { Param( [string[]]$ComputerName, [string]$LogFailuresToPath, [string]$Protocol = "Wsman", [switch]$ProtocolFallback ) foreach ($computer in $computername) { if ($protocol -eq 'Dcom') { #1 $option = New-CimSessionOption -Protocol Dcom } else { $option = New-CimSessionOption -Protocol Wsman } $session = New-CimSession -ComputerName $computer #2 -SessionOption $option # $os = Get-CimInstance -ClassName Win32_OperatingSystem #3 -CimSession $session $session | Remove-CimSession #4 $os | Select-Object -Prop @{n='ComputerName';e={$computer}}, #5 Version,ServicePackMajorVersion } #foreach } #function #1 Establishes session protocol #2 Connects the session #3 Queries data #4 Closes the session #5 Outputs the data
Compare the original Get-MachineInfo function with a pipeline-enabled design, then adapt its focused connection, query, cleanup, and output steps. section 17.1.3
