How do you write a powershell function that reads data from nested channels?

SOLVE:

The following are the simplest examples of functions / scripts that use an input channel. Each of them behaves the same way as the pipeline into the echo cmdlet.

Like 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 } } 

Like scripts:

# Echo-Pipe.ps1
  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 } 
# Echo-Pipe2.ps1
 foreach ($i in $input) { $i } 

eg.

 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 
+6
source share
1 answer

You also have the option to use advanced features instead of the basic approach above:

 function set-something { param( [Parameter(ValueFromPipeline=$true)] $piped ) # do something with $piped } 

Obviously, only one parameter can be associated directly with pipelined input. However, you can have several parameters that communicate with different properties when entering a pipeline:

 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 explore another shell.

+12
source

Source: https://habr.com/ru/post/910128/


All Articles