Blogroll

Search

Functions with process blocks versus functions without process blocks.

October 4th, 2011 by Karl

What’s the difference between a function with a process block versus one without?

When you have a process block

  • you can have a begin and end as well (optionally)
  • the process block is called for each item in the pipeline and you can reference it via $_ (if a simple function, otherwise through a parameter with ValueFromPipeline from an advanced function)
  • you can’t access $input (you have $_ in process instead)
function fullfunction
{
 begin 
  {
   write-warning "in begin"
   "from beginning"
  }
 process
  {
   write-warning "in process $_" 
   "from process"
  }
 end
  {
   write-warning "in end"
   "from end"      
  }
}
1..3 | fullfunction

image

When you don’t have a process block

  • Its effectively an END block
  • you break streaming of the pipeline. So if you have 1..10 | streaming-something | mydumbfunction | streaming-somethingelse  the dumbfunction stops streaming and doesn’t output anything to the downstream until the end.
  • you can reference the COMPLETE pipeline input with $input
  • you can a end block and put the code in that (same effect)
function simplefunction
{
 end {
 $input | % { "processing each item in $input with foreach $_ " }
 }
}
1..5 | simplefunction

processing each item in 1 with foreach 1 
processing each item in 2 with foreach 2 
processing each item in 3 with foreach 3 
processing each item in 4 with foreach 4 
processing each item in 5 with foreach 5 

Posted in Powershell | 1 Comment »

One Response

  1. Tahir Hassan Says:

    I think it is also worth mentioning that Filters behave in a similar way:

    * No BEGIN, PROCESS, END blocks -> Same as a PROCESS block -> Streaming
    * END block only -> Breaks Streaming

    By default, Filters stream, Functions block streaming.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.