Guy recommends :
Free Solarwinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



How to Create a PowerShell Function

How to Create a PowerShell Function

This is a good time to think about your approach to PowerShell's functions.  Are they a tool to be used occasionally for recurring blocks of code?  Alternatively, will functions become the central methodology for every script you create.

To elaborate what I mean, let us consider three statements from people with different scripting knowledge:

  1. For beginners - Functions are mysterious even mythical.
  2. For intermediates - Functions are a method of saving time when tackling repetitive tasks.
  3. For experts - Functions are a way of life.  They consider a functions as a building block in their master plan to build scripts.

Topics for PowerShell's Functions

 ♣

Guy's Mission

I have an aversion to using 'Hello World' examples.  Instead, Guy has invented a basic 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 Get-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. 

Example 1 - A PowerShell Function to Calculate Baseball Averages

Here is a classic example for dissecting, fiddling, changing stuff to see what happens, and thus truly learning how functions are constructed.  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 main curly 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.

# PowerShell function example script: Calculate batting average
# Author: Guy Thomas
function Get-BatAvg
{param ([string]$Name, [int]$Hits, [int]$AtBats)
$Avg = [int]($Hits / $AtBats*100)/100
if($Avg -gt 1) {
Write-Output "$Name's cricket average = $Avg : $Hits Runs, $AtBats dismissals"
       }
else {
Write-Output "$Name's baseball average = $Avg : $Hits Hits, $AtBats AtBats"
       }
}

Get-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:
Get-BatAvg -AtBats 70 -hits 6999 -name Babe.  (Default order -Name -Hits -AtBats)

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.

Guy Recommends: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.  Fortunately, Solarwinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.  Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server.

Download your free copy of WMI Monitor

Example 2 - A Function to Calculate A Cricket Batting Average

The point of this script is to create a function called Get-BatAvg which calculates a batsman's average.  You need to supply three parameters, a name, the number of runs, and the number of dismissals.  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
# Author: Guy Thomas
# Version 2.2  June 2008 tested on PowerShell v 1.0
Function Get-BatAvg
{param ($Name, $Runs, $Outs)
$Avg = [int]($Runs / $Outs*100)/100
Write-Output "$Name's Average = $Avg, $Runs, $Outs"
}

Get-BatAvg Bradman 6996 70

Note 5:  The last line calls for the function Get-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 6:  Each param is separated by a comma.

Note 7:  When you explicitly declare with param, it must be the very first word inside the curly bracket.

Guy Recommends:  Solarwinds' Free Bulk Import ToolFree Download of Solarwinds  Bulk Import Tool

Import users from a spreadsheet.  Just provide a list of the users with their fields in the top row, and save as .csv file.  Then launch this FREE utility and match your fields with AD's attributes, click to import the users.  Optionally, you can provide the name of the OU where the new accounts will be born.

There are also two bonus tools in this free download, and all 3 have been approved by Microsoft:

  1. Bulk-import new users into Active Directory.
  2. Seek and zap unwanted user accounts.
  3. Find inactive computers.

Download your FREE bulk import tool.

Researching the Primary Key for a WMI Class

Here is a completely different function example, which is nothing to do with batting averages.  In this case we need a specialist function that displays the primary key for a particular WMI Class.

# Function to Discover WMI Primary Keys
Clear-Host
Function Get-WmiKey
{
$Class = [WmiClass]$args[0]
$Class.Properties | `
Select @{Name="PName";Expression={$_.name}} -Expand Qualifiers | `
Where {$_.Name -eq "key"} | `
foreach {$_.Pname}
}

Get-WmiKey Win32_LogicalDisk

Note 8:  The whole point of creating this function is that you can substitute any WMI class for Win32_LogicalDisk.

Note 9:  See more on the use of this function with WMI [TYPE}

More Help For Creating PowerShell Functions

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 words at the command line:

Clear-Host
Get-Help About_function

Note 10:  That's an underscore not a dash, also appreciate that 'function' is singular.

PowerShell Function to Sum an Array

A popular quiz question is what's the total of all the numbers on a roulette wheel?  Here is a solution using a PowerShell function.

$x = 1..100
function Get-Sum ($a) { return ($a | Measure-Object -Sum).Sum}

Get-Sum (1..36)

Incidentally, my friend 'Mad' Mick solved the problem with pencil and paper using this formula:

$y = 36
$z = ($y * $y)*2 + $y.  Simplifies to: (36 * 18) +18 = 666.

Summary of PowerShell's Functions

Scripting 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. 

If you like this page then please share it with your friends

 


See more PowerShell examples for syntax constructions

PowerShell Tutorials  • Syntax  • Pipeline  • Quotes  • New-Item  • Remove-Item  • ItemProperty

Select-String  • -replace string  • Group-Object  • Sort-Object 

Windows PowerShell cmdlets   • Windows PowerShell

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Custom Search

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, Solarwinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

 

Home Copyright © 1999-2012 Computer Performance LTD All rights reserved

Please report a broken link, or an error.