Powershell – So what *IS* a function?

Powershell

The whole point of Powershell is to make your life, to be blunt, EASIER and more efficient.

One of the nice simple and easy to work with features of Powershell is what is referred to as a “Function” (Yes you can picture some “Austin Powers Dr. Evil” finger quotes as I said that.

A “Function” is a lot like a small script to repeat a task you might do on a regular basis.   It can be part of script too.  It’s job is to simply put it, perform a “Function”

What is a function?  It could be as complex as a script, but really doesn’t need to be.

Really if you find yourself repeating a Sequence of commands over and over and over?  A lot of that might become a simple function.

Let’s just say you have a script like this… A simple one…

 

———- sillyscript.ps1 ————–

$INFO=READ-HOST ‘Gimme some input:’

for ($i in 1..20)
{
$WRITE-HOST $INFO
}

$INFO=READ-HOST ‘Gimme more input:’

for ($i in 1..20)
{
$WRITE-HOST $INFO
}

$INFO=READ-HOST ‘Gimme even more input:’

for ($i in 1..20)
{
$WRITE-HOST $INFO
}

 

—————- sillyscript.ps1 ——————-

 

Of course this is a completely pointless script.  Ask for input, write that input on the screen 20 times.   It’s almost like something from the Commodore PET!

 

But you CAN see we are repeating ourselves.   Where what we can do is take most of this and turn it into a function.   A function is just another Script block but you’re giving it a name a telling it what it can receive, and possibly return.

 

So we can write the For loop as a function and just simply call it up.  You just place the definition for the function at the beginning of the script and call it up whenever it’s needed.  Our new sillyscript.ps1 will look like THIS instead. 

————— sillyscriptv2.ps1 —————–

function loopyprinter ($DATA)

{

for ($i in 1..20)
{
$WRITE-HOST $DATA
}

}

$info=READ-HOST ‘Gimme some input:’

loopyprinter($info)

$info=READ-HOST ‘Gimme more input:’

loopyprinter($info)

$info=READ-HOST ‘Gimme even more input:’

loopyprinter($info)

 

—————sillyscriptv2.ps1 ————————–

 

Of course this script only serves one point.  To show you how a function can simplify a script by controlling repeated code and of course just how pointless printing your name on the screen 20 times is.

 

But you can see, it’s NOT difficult.  In fact, it’s absolute painless, even if my script is absolutely pointless 🙂

 

Sean
The Energized Tech

Leave a Reply