Pipeline input

A question on the forum asked about creating a function that accepts pipeline input OR has a path parameter.  Means it can be used like this

myfunction -Path C:\scripts\Test\proc.csv

or

(Get-Content C:\scripts\Test\files.txt) | myfunction

First create a csv file

Get-Process | Export-Csv proc.csv –NoTypeInformation

and test its contents

Import-Csv proc.csv

The full path to the csv file is:-  C:\scripts\Test\proc.csv

The function is like this

function myfunction{             
[CmdletBinding()]             
param (             
[parameter(ValueFromPipeline=$true,             
   ValueFromPipelineByPropertyName=$true)]            
   [string]$Path            
)             
PROCESS{            
 if (-not (Test-Path -Path $path)){            
   Throw "Path NOT found $path"            
 }            
            
 Import-Csv -Path $path            
            
}#process             
            
}

Use [CmdletBinding()] to get the debug and verbose parameters

Use ValueFromPipeline and ValueFromPipelineByPropertyName attributes [parameter()]

This covers generic input and if we have a csv with path as a column.

if you are accepting pipeline input you need to use a PROCESS block

Then the path is tested and rejected if not valid. Finally import-csv is used to read the file

Published Wed, Jun 13 2012 22:35 by RichardSiddaway
Filed under:

Comments

# re: Pipeline input

And if you are implementing only Process block, you can use 'filter', instead of 'function'. Filters are the same function with the only Process block. Filters cannot implement Begin/End blocks:

filter myfilter{

[CmdletBinding()]            

  param (

     [Parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName=$true)]

     $path

  )

  #if (-not (Test-Path -Path $path)) {

   #  Throw "Path NOT found $path"

  #}

  #Import-Csv -Path $path

$path.name

}

Sunday, June 17, 2012 1:47 AM by Vadims Podans

# re: Pipeline input

I would not recommend using filter.

They don't really add anything and can become confusing

Friday, June 22, 2012 7:08 AM by RichardSiddaway

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: