Creating a Powershell function

We can create commands/cmdlets using C# or combine commands in ps1 files (for example) but we can also implement Powershell functions, which give is the ability to combine existing Powershell commands but wrap them in their own function with their own help etc.

Let’s look at a simple implementation of a tail-like command

Get-Content -Path c:\logs\logfile.log -Wait 

Ofcourse the first thing we might like to do is wrap this in a simple function, like this

function Get-Tail 
{ 
   Get-Content -Path $args[0] -Wait 
}

This works fine, but now maybe we’d like to make it more obvious what argument(s) Get-Tail expects. So we’ll add a parameter which better illustrates the intent via it’s name etc. So now we might have

function Get-Tail 
{ 
   param (
      [Parameter(Mandatory=$true, 
       Position=0, 
       HelpMessage="Path of file to tail")]
      [ValidateNotNullOrEmpty()]
      [string]$Path
   )

   Get-Content -Path $Path -Wait 
}

Here we’ve named the parameter that we expect as Path and we’ve stipulated it’s type. We’ve also added a Parameter attribute to ensure it’s obvious that this is a mandatory field and if the user forgets to supply it, Powershell will ask for it, to that purpose we’ve also supplied a help message so if the user types !? into the prompt for Path, the user will get the help message telling them what’s expected.

This is looking good, but running Get-Help tells us very little about the function so now we can extend this further and make it look like this

function Get-Tail 
{ 
<#
.SYNOPSIS
   Lists the file to standard out and waits 
   for any change which are then also output
.DESCRIPTION
   Get-Tail works a little like the tail 
   command, it allows the user to write a 
   file to standard out and then waits for
   any further changes, these to are written to
   standard out until the user exist the command.
.PARAMETER Path
   The Path to the file to be tailed
.EXAMPLE
   Get-Tail c:\logs\logfile.log
#>
param
(
[Parameter(Mandatory=$true, 
 Position=0, 
 HelpMessage="Path of file to tail")]
[ValidateNotNullOrEmpty()]
[string]$Path
)
 
Get-Content -Path $Path -Wait 
}

Now we have a command written in Powershell which looks and acts like any of the common commands might work, with help.

Let’s quickly review the lines we’ve added – the <# #> is the comment block for Powershell, within it we’ve headings along the lines of .HEADING and below that we’ve just some text to describe the command. The .PARAMETER is more interesting in that we write the parameter name after it (we can have multiple .PARAMETER blocks for multiple params).

To find out what options are available for the help block, type

Get-Help about_Comment_Based_Help

References

Documenting Your PowerShell Binary Cmdlets