Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a PowerShell script that accepts pipeline input?

Tags:

powershell

I am trying to write a PowerShell script that can get pipeline input (and is expected to do so), but trying something like

ForEach-Object {    # do something } 

doesn't actually work when using the script from the commandline as follows:

1..20 | .\test.ps1 

Is there a way?

Note: I know about functions and filters. This is not what I am looking for.

like image 202
Joey Avatar asked May 19 '09 22:05

Joey


People also ask

How do I use piping in PowerShell?

The `|` character in between the two commands is the “pipe” which indicates that instead of displaying the output of the Get-Content command in the PowerShell command window, it should instead pass that data to the next script (the Measure-Object cmdlet).

What do you need to define in a function in order to use pipelined input?

However, it wasn't until PowerShell came along that we had a language that allowed us to pipe objects from one command to another. For a function to accept pipeline input, it needs to be an advanced function.

What is pipeline function in PowerShell?

There are a number of ways how your PowerShell functions can accept pipeline input. Pipeline-aware functions unleash the real flexibility of PowerShell command composition. One of the most powerful features of PowerShell is its ability to combine commands via the pipeline operator.


1 Answers

In v2 you can also accept pipeline input (by propertyName or byValue), add parameter aliases etc:

function Get-File{     param(       [Parameter(         Position=0,          Mandatory=$true,          ValueFromPipeline=$true,         ValueFromPipelineByPropertyName=$true)     ]     [Alias('FullName')]     [String[]]$FilePath     )       process {        foreach($path in $FilePath)        {            Write-Host "file path is: $path"        }     } }   # test ValueFromPipelineByPropertyName  dir | Get-File  # test ValueFromPipeline (byValue)   "D:\scripts\s1.txt","D:\scripts\s2.txt" | Get-File   - or -  dir *.txt | foreach {$_.fullname} | Get-File 
like image 129
Shay Levy Avatar answered Oct 01 '22 12:10

Shay Levy