Posts RSS Comments RSS 253 Posts and 411 Comments till now

The Beginning and the End (the process to)

In my powershell journeys I have found a huge quantity of glorious abilities wrapped up in this truly POWER shell. One of these superpowers is the concept of filter/function processing. While I do not consider myself a guru in any stretch I have done a good bit of work with functions and think I have a sound grasp of this ability.

I haven’t used filters that much so I will stick with what I know… functions. Oh… glorious functions! These have been the life blood of my powershell experience. I came from a VBScript back ground and have always been super anal (or lazy) about code reuse. I would always try to black box my code to be able to reuse later. While this is a good practice IMHO… it does tend to get lost sometimes… This is where I believe Powershell functions come in.

There a ton of things you can do with functions and I don’t have time to discuss them all, so I am going to focus on my favorite…. Begin, Process, and End oh my!

Lets start with the basic layout of a function:

function foo{
   write-host "Hello World"
}

Ok… nothing spectacular there, but what if I want to be more specific to whom I say hello

function foo{
   param([string]$name)
   Write-Host "Hello $name"
}

This is nice… but still… nothing big going on. I mean seriously… what kinda scripting language can’t a take parameters.

function foo{
   Param([string]$name)
   Begin{
       # Only gets process at the Beginning
       # Normally include Variable creation and functions
       Write-Host "Starting"
   }
   Process{
      # Gets process for each object in the pipe (if ones exist)
      if($_){Write-Host "Hello $_"}
   }
   End{
      # Always get processed once at the end
      if($name){Write-Host "Hello $name"}
   }
}

Now… as trivial as this looks this function is truly amazing. It not only has the ability to take a parameter, but it can also take a pipe (pipe is explained below.)

Like I said, functions of lots of abilities but this is my favorite. Thanks to Jeffrey and the Team…. GREAT IDEA!!!

===============================================
pipe: A pipe is when you get the results of one command and pipe them to another… Kinda like you did in DOS or BASH, but instead of pass text… in powershell you pass objects.

2 Responses to “The Beginning and the End (the process to)”

  1. on 04 Apr 2010 at 1:20 pmtomasa

    Thanks Brandon~
    Your blog is great!!!

  2. on 04 Apr 2010 at 1:21 pmtommy

    Thanks Brandon.

    Your blog is great!

Trackback this post | Feed on Comments to this post

Leave a Reply

You must be logged in to post a comment.