PowerShell Function Parameters: A Practical Guide to Building Better Functions

Published:30 December 2024 - 4 min. read

Building functions in PowerShell is a great way to make your scripts modular and reusable. But if you want those functions adaptable in different scenarios, adding function parameters can take them to the next level.

In this tutorial, we’ll expand on a basic logging function by adding parameters to control the log message, file path, and validation.

By the end, you’ll see how parameters can make your functions versatile, error-resistant, and powerful additions to your PowerShell toolkit.

Defining the Basic Write-Log Function

We’ll start with a basic function that takes a single input parameter for the log message and appends it to a standard log file with a timestamp.

In this example:

  • The $LogMessage parameter is marked as mandatory, so PowerShell prompts it if you don’t provide a value.
  • Each log entry includes a timestamp formatted as HH:mm:ss.
function Write-Log {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$LogMessage
    )
    $timeGenerated = Get-Date -Format HH:mm:ss
    Add-Content -Path "C:\Scripts\software_installer.log" -Value "$timeGenerated - $LogMessage"
}

Testing the Write-Log Function

Now that the Write-Log function has a basic structure and accepts parameters, it’s time to test its functionality. Testing helps ensure that each aspect of the function, from default settings to custom inputs, performs as expected and handles errors gracefully.

Test the Write-Log function by calling it with a custom message:

Write-Log -LogMessage 'Testing a new log message'

This command adds a new entry with a timestamp to the log file (C:\Scripts\software_installer.log).

A few things to notice about the Write-Log function:

Standardized Information Logging By setting a default path for the log file, you don’t have to specify the file name every time you call the function. This standardizes all log information to a single file, keeping your logs organized.
Simplified Logging Process The function abstracts away details like getting the current date and time with Get-Date and appending content with Add-Content. As a user of the function, you can focus solely on writing messages to the log file without needing to remember these details.
Improved Code Readability The function explicitly logs messages to a designated log file, making it clear that the purpose is logging rather than simply writing to a generic text file. This makes the code more self-explanatory and easier to understand at a glance.

With these improvements, the Write-Log function helps streamline logging tasks, making scripts cleaner and more maintainable.

You can view the latest log message by checking the contents of the log file:

Get-Content -Path "C:\Scripts\software_installer.log"

This command displays all log entries, including your latest message with a timestamp.

But perhaps you accidentally called Write-Log without a LogMessage parameter:

Write-Log

You’ll notice that—because LogMessage is required—PowerShell will prevent the function from running. But, if LogMessage weren’t mandatory, an empty message would be written, creating an unintended “oops” entry.

Verify the result by rechecking the log file:

Get-Content -Path "C:\Scripts\software_installer.log"

Adding Flexibility with a Custom Log File Path

While the function works great, let’s make it even more flexible by adding a $LogFilePath parameter. This parameter allows you to specify a custom file path while providing a default path.

function Write-Log {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$LogMessage,

        [Parameter()]
        [string]$LogFilePath = 'C:\Scripts\software_installer.log'
    )
    $timeGenerated = Get-Date -Format HH:mm:ss
    Add-Content -Path $LogFilePath -Value "$timeGenerated - $LogMessage"
}

Notice that $LogFilePath has a default path of C:\Scripts\software_installer.log, but you can provide any valid path.

To specify a different file path, call Write-Log like this:

Write-Log -LogMessage 'Custom path log message' -LogFilePath 'C:\Scripts\custom_log.log'

Enforcing the File Path with ValidateScript

You don’t want your function to log files that don’t exist. For that matter, you can ensure the file exists before logging by using the ValidateScript parameter attribute. This attribute allows you to run code against a parameter’s value, verifying it before running the function.

function Write-Log {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$LogMessage,

        [Parameter()]
        [ValidateScript({ Test-Path -Path $_ })]
        [string]$LogFilePath = 'C:\Scripts\software_installer.log'
    )
    $timeGenerated = Get-Date -Format HH:mm:ss
    Add-Content -Path $LogFilePath -Value "$timeGenerated - $LogMessage"
}

With ValidateScript, Write-Log checks that the file path you provide exists. If the file doesn’t exist, PowerShell stops and returns an error.

You can create an empty file before calling it to make sure the function works as expected:

Set-Content -Path 'C:\Scripts\softwarex_installer.log' -Value ''
Write-Log -LogMessage 'Log entry in a new file' -LogFilePath 'C:\Scripts\softwarex_installer.log'

Testing Write-Log Functionality and Validations

After adding flexibilities to your function, it’s only natural to test whether it works as intended. You must ensure robust logging functionality by examining the ValidateScript attribute and see how it enhances your Write-Log function.

Let’s see how ValidateScript works by trying to log into a non-existent file:

Write-Log -LogMessage 'Finishing install...' -LogFilePath 'C:\Scripts\softwarex_installer.log'

In this case, the ValidateScript attribute checks if the specified log file path exists by calling Test-Path. If the path doesn’t exist, the function returns an error.

The function fails because C:\Scripts\softwarex_installer.log doesn’t exist. You can verify this by running Test-Path manually:

Test-Path 'C:\Scripts\softwarex_installer.log'

Since Test-Path returns $false, the file is indeed missing.

To fix this, create a blank log file and test again.

Set-Content -Path 'C:\Scripts\softwarex_installer.log' -Value ''
Write-Log -LogMessage 'Finishing install...' -LogFilePath 'C:\Scripts\softwarex_installer.log'

Now, the function works as expected.

Confirm the result by viewing the log file:

Get-Content -Path 'C:\Scripts\softwarex_installer.log'

Using ValidateScript and other parameter validation attributes enforces the correct usage of function parameters, reducing errors and making your PowerShell functions more reliable.

Conclusion

Adding parameters to PowerShell functions greatly enhances their flexibility and usefulness. With a combination of default values, mandatory attributes, and validation, your functions can handle a variety of inputs while maintaining reliability.

Using these techniques, you can now build scalable, user-friendly functions that fit seamlessly into various scripts.

Expand on these skills as you create more advanced PowerShell tools to streamline and enhance your workflow. Check out this PowerShell Parameters tutorial and go deeper into function parameters!

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!