Ezine 164 - How to Create a PowerShell's FunctionEzine 164 - How to Create a PowerShell's FunctionWith functions, the key question should be, 'How come PowerShell deduces so much from so little information? And not, 'Why is the Function command so picky about syntax? One pleasant by-product of creating functions is that you will REALLY understand the way that built-in cmdlets use parameters. Topics for PowerShell's Functions
This week's SecretFunctions raise matters of philosophy about scripting in general, and PowerShell in particular. To amplify what I mean, let us start with three statements about people with different scripting knowledge. To beginners - Functions are mysterious even mythical. To intermediates - Functions are a method of saving time when tackling repetitive tasks. To experts - Functions are a way of life. They consider functions as building blocks in their master plan to build clever scripts. Now is a good time for us to decide our attitude to PowerShell's functions. Are they a tool to be used occasionally for recurring blocks of code? Or will functions become the central methodology for every script we create. For my part, one day I may aspire to making functions a way of scripting life, but for now that seems a bit scary, so I will stick to using functions as and when I can see a task that would benefit from this approach. Guy's MissionGuy has an aversion to employing 'Hello World' examples. Instead, I have invented a simple function to calculate batting averages. I realise that my hybrid example may please neither cricket lovers nor baseball aficionados. Casting aside sporting loyalties, these two scripts will get you started with PowerShell's functions. By using keyboard input, we are going to take two numbers and divide the first number by the second, and thus calculate the average in traditional math fashion. Before we get down to using my BatAvg Function, here are a few considerations. PowerShell dictates a format consisting of three parts, the keyword 'Function', followed by a name of your choice, finally, the payload containing the script block, which is enclosed by curly, or parenthesis style brackets. What you place inside the script block is the same code that you could execute normally outside the scope of the function. The whole point is that you can execute this block of PowerShell code simply by typing the name of the function. When you invest time in creating PowerShell functions, the benefits are as follows: firstly, you can repeat the block of code easily and reliably by calling the Function's name again and again. Secondly, you can introduce parameters which modify the code, for example, to change a name or a numeric value within the code block. In PowerShell, learning about the 'function' command is easy; to get started
type these two words at the command line: Example 1 - A function to calculate your batting averageThe point of this script is to create a function called BatAvg which calculates your batting average. You need to supply three parameters, a name, the number of runs, and the number of outs. My default settings are for the English game of cricket, however, for baseball, you could modify the Param $outs to $AtBats, and $runs to $Hits. # Microsoft PowerShell script to create a simple function function BatAvg {param ($Name, $Runs, $Outs) $Avg = [int]($Runs / $Outs*100)/100 Write-Output "$Name's Average = $Avg, $Runs, $Outs " BatAvg Bradman 6996 70 Note 1: The last line calls for the function BatAvg and inputs the three parameters. It would make my day if you altered the name 'Bradman' and then used two different numbers instead of 6996 and 70. Note 2: Each param is separated by a comma. Note 3: When you explicitly declare with param, it must be the very first word inside the curly bracket. ˆ Example 2 - A function to calculate baseball averagesThis example is a classic for dissecting, fiddling, changing stuff to see what happens and thus learn about functions. I re-jigged the first script to make it more suitable for baseball. Often, looking at two slightly different scripts gives you 'binocular vision', as a result you get extra insights into the techniques. It's good scripting technique to scope the parameters with the [String] or [Int]. Incidentally, square brackets mean optional information. $Avg = [int]($Runs / $Outs *100)/100 simply applies some maths to display the average to two decimal places. I wanted to introduce logic to help Americans who are thinking baseball 'outs', and Englishmen who are thinking cricket 'dismissals'. Observe how inside the maincurly brackets are {if... } and {Else... } blocks. My hidden agenda is to make you aware that you can put all sorts of scripting 'stuff' inside those curly brackets. # Microsoft PowerShell script to create a baseball batting average
function {param ([string]$Name, [int]$Hits, [int]$AtBats) BatAvg -name Babe -Hits 2873 -AtBats 7530 Note 1: Observe the relationship between declaring the param $name, and employing the parameter -name. Note 2: Another advantage of Param is that you can try
different sequences, for example: Note 3: The If... Else logic assumes that cricket averages are greater than one, but baseball averages are less than one. Note 4: Please pay close attention to the type of bracket. Also 'Single' or "double" quotes are highly significant. If you are looking for handy network utilities, try some of the free downloads at Tools4Ever Summary of PowerShell's FunctionsScripting functions are like macros, they replay your commands. In the case of PowerShell, you could also make functions the rational, framework or building-block for creating your scripts. When you get down to creating functions it reinforces knowledge of parameters. My subsidiary reason for explaining functions in this ezine is to reinforce the importance of employing the correct type of bracket, and paying attention to single and double quotes. See more PowerShell examples of syntax• PowerShell Home • Syntax • Loops • Variables • What If • Functions • Replace • PowerShell Please write in if you see errors of any kind. Please report any factual mistakes, grammatical errors or broken links, I will be happy to not only to correct the fault, but also to give you credit.
*
|
||||||