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.
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With