Functions in PowerShell: Building Better Commands

Posted by:

|

On:

|

Functions are repeatable steps that you can use as commands. Is there a something you need to do but no module to get it from? You’re in luck, because you can create your own!

Functions, like in arithmetic, are steps give output. Let’s say that I wanted to make a function that will tell me how many files are in my current directory. Here’s how you could do this manually:

PowerShell
$FileCount = (Get-ChildItem).count
Write-Output("There are " + $FileCount + " items in your current directory.")

Now let’s write a function to perform this for us. As a best practice, you should have a prefix that goes between the verb and command to avoid conflicts with default cmdlets or those from other installed modules. Here I’ll make the prefix “Wiz”.

PowerShell
function Get-WizFileCount {
$FileCount = (Get-ChildItem).count
    Write-Output("The directory " + $pwd + "contains " + $FileCount + " files.")
}

After defining the function, we can trigger it like so:

PowerShell
Get-WizFileCount

This can keep your code neat and reduce space if there is a repeatable task. If we want to add parameters to the function, we can make the most out of it. We can insert parameters inside param(). I’ve created two parameters, one is $MaxCount, which is an integer, and the other is $Path, which is a mandatory string of characters.

I added some conditional statements and comparison operators here.

PowerShell
function Get-WizFileCount {
    param(
        [int]$MaxCount = -1, # This makes -1 the default value
        [Parameter(Mandatory=$true)]
        [string]$Path # Mandatory parameters cannot have default values
    )
    $FileCount = (Get-ChildItem -Path $Path -File).Count
    if ($MaxCount -eq -1) {
        Write-Output("The folder $Path contains $FileCount files.")
    }
    else {
        if ($FileCount -gt $MaxCount) {
            Write-Output("The folder $Path contains more than $MaxCount files.")
        }
        else {
            Write-Output ("The folder $Path contains $FileCount files.")
        }
    }
}

There are two ways we can input a parameter into this function. We can run it as is or place the parameter in manually.

PowerShell
Get-WizFileCount # Prompts for values of missing mandatory parameters
Get-WizFileCount -Path "C:\Users\Public" # Just works

There is more to learn about functions but it’s hard to cover without getting into the weeds.

Advanced Functions, Cmdlets, and Modules

Advanced functions allow for more debugging and flexibility with your custom commands. Eventually, you may want to create Cmdlets, which are more mature versions of functions, or possibly even modules, to store the functions and variables. You can look online for public repositories by PowerShell developers and see how they make the modules if you’re interested. We’ll circle back to Advanced Functions eventually.