Monday, August 6, 2012

Easy PowerShell 5: Functions


Function doSomething($var = $null)
{
                $var2 = Read-host “Is it raining?”
                If($va2[0] -like “y”)
                {
                                $thing = “slimey”
                }
                Else
                {
                                $thing = “rought”
                }
}
Functions do things.  They don’t have to return anything, but they often do.  They don’t have to perform evaluations, but they often do.  They are way to store logic for later use.

In the example above, the doSomething function takes a parameter of var with a default value of $null.  That means when you call the function later on in your code, you’ll call it as dosomething -var “input”, or if a null value for $var is okay for you, just dosomething.

It then sets an internal variable of $var2 using whatever the user types in response to the prompt “Is it raining?”  The Read-Host cmdlet tells powershell to display whatever follows in quotes, then wait for the user to enter something.
Then the function evaluates what gets entered.  The if block will be executed if the first character in whatever you entered is “Y”or “y”.  The [0] notation treats the string you entered as an array of characters, and as with all good, and many less good, programming languages, PowerShell arrays are zero-indexed.  This means the first element is element 0, the second element is element 1, the third element is element 2, etc.  It’s reference to zero as source, and all sorts of other geekery that’s not really important in this context.

The if block sets the value of $thing (remember that from yesterday) to “slimey”.  However, when the user enters anything not beginning with “y”, like when the type “no”, the else block executes and the value of $thing is set to “rough”.

Please send me suggestions for some complex evaluations for our baseball analogy.  I’m not actually much of a baseball fan, so I’m starting to run dry on that topic.

My next write up will hopefully use your suggestions to write a useful baseball function.

No comments:

Post a Comment

I look forward to your feedback and questions. The rules for commenting are simple. No personal attacks against other commenters. No threats.