How do you write a powershell function that reads from piped input?
You also have the option of using advanced functions, instead of the basic approach above:
function set-something {
param(
[Parameter(ValueFromPipeline=$true)]
$piped
)
# do something with $piped
}
It should be obvious that only one parameter can be bound directly to pipeline input. However, you can have multiple parameters bind to different properties on pipeline input:
function set-something {
param(
[Parameter(ValueFromPipelineByPropertyName=$true)]
$Prop1,
[Parameter(ValueFromPipelineByPropertyName=$true)]
$Prop2,
)
# do something with $prop1 and $prop2
}
Hope this helps you on your journey to learn another shell.
samthebest
To make me answer a question I like to answer questions on Spark, Hadoop, Big Data and Scala. I'm pretty good at Bash, git and Linux, so I can sometimes answer these questions too. I've stopped checking my filters for new questions these days, so I'm probably not answering questions which I probably could. Therefore if you think I can help, especially with Spark and Scala, then rather than me give me email out, please comment on a similar question/answer of mine with a link. Furthermore cross-linking similar questions can be nice for general SO browsing and good for SEO. My favourite answers Round parenthesis are much much better than curly braces http://stackoverflow.com/a/27686566/1586965 Underscore evangelism and in depth explanation http://stackoverflow.com/a/25763401/1586965 Generalized memoization http://stackoverflow.com/a/19065888/1586965 Monad explained in basically 2 LOCs http://stackoverflow.com/a/20707480/1586965
Updated on June 16, 2022Comments
-
samthebest almost 2 years
SOLVED:
The following are the simplest possible examples of functions/scripts that use piped input. Each behaves the same as piping to the "echo" cmdlet.
As functions:
Function Echo-Pipe { Begin { # Executes once before first item in pipeline is processed } Process { # Executes once for each pipeline object echo $_ } End { # Executes once after last pipeline object is processed } } Function Echo-Pipe2 { foreach ($i in $input) { $i } }
As Scripts:
# Echo-Pipe.ps1
# Echo-Pipe2.ps1Begin { # Executes once before first item in pipeline is processed } Process { # Executes once for each pipeline object echo $_ } End { # Executes once after last pipeline object is processed }
foreach ($i in $input) { $i }
E.g.
PS > . theFileThatContainsTheFunctions.ps1 # This includes the functions into your session PS > echo "hello world" | Echo-Pipe hello world PS > cat aFileWithThreeTestLines.txt | Echo-Pipe2 The first test line The second test line The third test line