There are clear-cut guidelines that can be used to design functions. These guidelines can be used to ensure that functions are easy to understand, easy to maintain, and easy to troubleshoot. This chapter from Windows PowerShell Step by Step, 3rd Edition examines the reasons for the scripting guidelines and provides examples of both good and bad code design.

After completing this chapter, you will be able to

Understand functions.

Use functions to provide ease of reuse.

Use functions to encapsulate logic.

Use functions to provide ease of modification.

There are clear-cut guidelines that can be used to design functions. These guidelines can be used to ensure that functions are easy to understand, easy to maintain, and easy to troubleshoot. This chapter examines the reasons for the scripting guidelines and provides examples of both good and bad code design.

Understanding functions

In Windows PowerShell, functions have moved to the forefront as the primary programming element used when writing Windows PowerShell scripts. This is not necessarily due to improvements in functions per se, but rather to a combination of factors, including the maturity of Windows PowerShell script writers. In Windows PowerShell 1.0, functions were not well understood, perhaps due to the lack of clear documentation as to their use, purpose, and application.

Microsoft Visual Basic Scripting Edition (VBScript) included both subroutines and functions. According to the classic definitions, a subroutine was used to encapsulate code that would do things like write to a database or create a Microsoft Word document. Functions, on the other hand, were used to return a value. An example of a classic VBScript function is one that converts a temperature from Fahrenheit to Celsius. The function receives a value in Fahrenheit and returns the value in Celsius. The classic function always returns a value—if it does not, a subroutine should be used instead.

NOTE

Needless to say, the concepts of functions and subroutines were a bit confusing for many VBScript writers. A common question I used to receive when teaching VBScript classes was, “When do I use a subroutine and when do I use a function?” After expounding the classic definition, I would then show them that you could actually write a subroutine that would behave like a function. Next, I would write a function that acted like a subroutine. It was great fun, and the class loved it. The Windows PowerShell team has essentially done the same thing. There is no confusion over when to use a subroutine and when to use a function, because there are no subroutines in Windows PowerShell—only functions.

To create a function in Windows PowerShell, you begin with the Function keyword, followed by the name of the function. As a best practice, use the Windows PowerShell verb-noun combination when creating functions. Pick the verb from the standard list of Windows PowerShell verbs to make your functions easier to remember. It is a best practice to avoid creating new verbs when there is an existing verb that can easily do the job.

An idea of the verb coverage can be obtained by using the Get-Command cmdlet and pipelining the results to the Group-Object cmdlet. This is shown here.

When the preceding command is run, the resulting output is as follows. This command was run on Windows 10 and includes cmdlets from the default modules. As shown in the listing, Get is used the most by the default cmdlets, followed distantly by Set, New, and Remove.

A function is not required to accept any parameters. In fact, many functions do not require input to perform their job in the script. Let’s use an example to illustrate this point. A common task for network administrators is obtaining the operating system version. Script writers often need to do this to ensure that their script uses the correct interface or exits gracefully. It is also quite common that one set of files would be copied to a desktop running one version of the operating system, and a different set of files would be copied for another version of the operating system. The first step in creating a function is to come up with a name. Because the function is going to retrieve information, in the listing of cmdlet verbs shown earlier, the best verb to use is Get. For the noun portion of the name, it is best to use something that describes the information that will be obtained. In this example, a noun of OperatingSystemVersion makes sense. An example of such a function is shown in the Get-OperatingSystemVersion.ps1 script. The Get-OperatingSystemVersion function uses Windows Management Instrumentation (WMI) to obtain the version of the operating system. In this basic form of the function, you have the function keyword followed by the name of the function, and a script block with code in it, which is delimited by braces. This pattern is shown here.

Function Function-Name
{
#insert code here
}

In the Get-OperatingSystemVersion.ps1 script, the Get-OperatingSystemVersion function is at the top of the script. It uses the Function keyword to define the function, followed by the name, Get-OperatingSystemVersion. The script block opens, followed by the code, and then the script block closes. The function uses the Get-CimInstance cmdlet to retrieve an instance of the Win32_OperatingSystem WMI class. Because this WMI class only returns a single instance, the properties of the class are directly accessible. The version property is the one you’ll work with, so use parentheses to force the evaluation of the code inside. The returned management object is used to emit the version value. The braces are used to close the script block. The operating system version is returned to the code that calls the function. In this example, a string that writes This OS is version is used. A subexpression is used to force evaluation of the function. The version of the operating system is returned to the place where the function was called. This is shown here.

Now let’s look at choosing the cmdlet verb. In the earlier listing of cmdlet verbs, there is one cmdlet that uses the verb Read. It is the Read-Host cmdlet, which is used to obtain information from the command line. This would indicate that the verb Read is not used to describe reading a file. There is no verb called Display, and the Write verb is used in cmdlet names such as Write-Error and Write-Debug, both of which do not really seem to have the concept of displaying information. If you were writing a function that would read the content of a text file and display statistics about that file, you might call the function Get-TextStatistics. This is in keeping with cmdlet names such as Get-Process and Get-Service, which include the concept of emitting their retrieved content within their essential functionality. The Get-TextStatistics function accepts a single parameter called path. The interesting thing about parameters for functions is that when you pass a value to the parameter, you use a hyphen. When you refer to the value inside the function, it is a variable such as $path. To call the Get-TextStatistics function, you have a couple of options. The first is to use the name of the function and put the value inside parentheses. This is shown here.

Get-TextStatistics("C:\fso\mytext.txt")

This is a natural way to call the function, and it works when there is a single parameter. It does not work when there are two or more parameters. Another way to pass a value to the function is to use the hyphen and the parameter name. This is shown here.

Get-TextStatistics -path "C:\fso\mytext.txt"

Note from the previous example that no parentheses are required. You can also use positional arguments when passing a value. In this usage, you omit the name of the parameter entirely and simply place the value for the parameter following the call to the function. This is illustrated here.

Get-TextStatistics "C:\fso\mytext.txt"

NOTE

The use of positional parameters works well when you are working from the command line and want to speed things along by reducing the typing load. However, it can be a bit confusing to rely on positional parameters, and in general I tend to avoid them—even when working at the command line. This is because I often copy my working code from the console directly into a script, and as a result, I would need to retype the command a second time to get rid of aliases and unnamed parameters. With the improvements in tab expansion, I feel that the time saved by using positional parameters or partial parameters does not sufficiently warrant the time involved in retyping commands when they need to be transferred to scripts. The other reason for always using named parameters is that it helps you to be aware of the exact command syntax.

One additional way to pass a value to a function is to use partial parameter names. All that is required is enough of the parameter name to disambiguate it from other parameters. This is illustrated here.

Between Windows PowerShell 1.0 and Windows PowerShell 2.0, the number of verbs grew from 40 to 60. In Windows PowerShell 5.0, the number of verbs remained consistent at 98. The list of approved verbs is shown here.

After the function has been named, you should specify any parameters the function might require. The parameters are contained within parentheses. In the Get-TextStatistics function, the function accepts a single parameter: -path. When you have a function that accepts a single parameter, you can pass the value to the function by placing the value for the parameter inside parentheses. This is known as calling a function like a method, and is disallowed when you use Set-StrictMode with the Latest value for the -Version parameter. The following command generates an error when the latest strict mode is in effect—otherwise, it is a permissible way to call a function.

Get-TextLength("C:\fso\test.txt")

The path C:\fso\test.txt is passed to the Get-TextStatistics function via the -path parameter. Inside the function, the string C:\fso\text.txt is contained in the $path variable. The $path variable lives only within the confines of the Get-TextStatistics function. It is not available outside the scope of the function. It is available from within child scopes of the Get-TextStatistics function. A child scope of Get-TextStatistics is one that is created from within the Get-TextStatistics function. In the Get-Text-StatisticsCallChildFunction.ps1 script, the Write-Path function is called from within the Get-Text-Statistics function. This means the Write-Path function will have access to variables that are created within the Get-TextStatistics function. This is the concept of variable scope, which is extremely important when working with functions. As you use functions to separate the creation of objects, you must always be aware of where the objects get created, and where you intend to use them. In the Get-TextStatisticsCallChildFunction, the $path variable does not obtain its value until it is passed to the function. It therefore lives within the Get-TextStatistics function. But because the Write-Path function is called from within the Get-TextStatistics function, it inherits the variables from that scope. When you call a function from within another function, variables created within the parent function are available to the child function. This is shown in the Get-TextStatisticsCallChildFunction.ps1 script, which follows.

Inside the Get-TextStatistics function, the $path variable is used to provide the path to the Get-Content cmdlet. When the Write-Path function is called, nothing is passed to it. But inside the Write-Path function, the value of $path is maintained. Outside both of the functions, however, $path does not have any value. The output from running the script is shown here.

You will then need to open and close a script block. A pair of opening and closing braces is used to delimit the script block on a function. As a best practice, when writing a function, I will always use the Function keyword, and type in the name, the input parameters, and the braces for the script block at the same time. This is shown here.

Function My-Function
{
#insert code here
}

In this manner, I make sure I do not forget to close the braces. Trying to identify a missing brace within a long script can be somewhat problematic, because the error that is presented does not always correspond to the line that is missing the brace. For example, suppose the closing brace is left off the Get-TextStatistics function, as shown in the Get-TextStatisticsCallChildFunction-DoesNOTWork-MissingClosingBrace.ps1 script. An error will be generated, as shown here.

The problem is that the position indicator of the error message points to the first character on line 28. Line 28 happens to be the first blank line after the end of the script. This means that Windows PowerShell scanned the entire script looking for the closing brace. Because it did not find it, it states that the error is at the end of the script. If you were to place a closing brace on line 28, the error in this example would go away, but the script would not work. The Get-TextStatisticsCallChildFunction-DoesNOTWork-MissingClosingBracket.ps1 script is shown here, with a comment that indicates where the missing closing brace should be placed.