Home > Sample chapters

Working with Functions in Windows PowerShell

Using more than two input parameters

When using more than two input parameters, I consider it a best practice to modify the way the function is structured. This not only makes the function easier to read, it also permits cmdlet binding. In the basic function pattern shown here, the function accepts three input parameters. When you consider the default values and the type constraints, you can tell that the parameters begin to become long. Moving them to the inside of the function body highlights the fact that they are input parameters, and it makes them easier to read, understand, and maintain. It also allows for decorating the parameters with attributes.

Function Function-Name
{
  Param(
        [int]$Parameter1,
        [String]$Parameter2 = "DefaultValue",
        $Parameter3
       )
#Function code goes here
} #end Function-Name

An example of a function that uses three input parameters is the Get-DirectoryListing function. With the type constraints, default values, and parameter names, the function signature would be rather cumbersome to include on a single line. This is shown here.

Function Get-DirectoryListing ([String]$Path,[String]$Extension = "txt",[Switch]$Today)

If the number of parameters were increased to four, or if a default value for the -Path parameter was wanted, the signature would easily scroll to two lines. The use of the Param statement inside the function body also provides the ability to specify input parameters to a function.

Following the Function keyword, the name of the function, and the opening script block, the Param keyword is used to identify the parameters for the function. Each parameter must be separated from the others by a comma. All the parameters must be surrounded with a set of parentheses. If you want to assign a default value for a parameter, such as the extension .txt for the Extension parameter in the Get-DirectoryListing function, you perform a straight value assignment followed by a comma.

In the Get-DirectoryListing function, the Today parameter is a switch parameter. When it is supplied to the function, only files written to since midnight on the day the script is run will be displayed. If it is not supplied, all files matching the extension in the folder will be displayed. The Get-DirectoryListingToday.ps1 script is shown here.

Get-DirectoryListingToday.ps1

Function Get-DirectoryListing
{
 Param(
       [String]$Path,
       [String]$Extension = "txt",
       [Switch]$Today
      )
 If($Today)
   {
    Get-ChildItem -Path $path\* -include *.$Extension |
    Where-Object { $_.LastWriteTime -ge (Get-Date).Date }
   }
 ELSE
  {
   Get-ChildItem -Path $path\* -include *.$Extension
  }
} #end Get-DirectoryListing

# *** Entry to script ***
Get-DirectoryListing -p c:\fso -t