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


(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{             
param (             
 if (-not (Test-Path -Path $path)){            
   Throw "Path NOT found $path"            
 Import-Csv -Path $path            

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

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s