---
title: "PowerShell Function Parameters: A Practical Guide to Building Better Functions"
description: "Learn how to enhance your PowerShell functions with parameters, from basic logging functions to advanced validation. This hands-on tutorial shows you how to make your functions more flexible and reliable."
canonical: "https://adamtheautomator.com/powershell-function-parameters/"
---

# PowerShell Function Parameters: A Practical Guide to Building Better Functions

> Learn how to enhance your PowerShell functions with parameters, from basic logging functions to advanced validation. This hands-on tutorial shows you how to make your functions more flexible and reliable.

Source: https://adamtheautomator.com/powershell-function-parameters/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![PowerShell Function Parameters: A Practical Guide to Building Better Functions](https://adamtheautomator.com/wp-content/uploads/2024/12/featured-image-6.webp)

# PowerShell Function Parameters: A Practical Guide to Building Better Functions

[![](https://secure.gravatar.com/avatar/d0b9d42e21e5622713f8b693aa5c0f9244d5f7dd200ed29b8398f52dee5de337?s=192&d=mm&r=g)Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)30 December 20244 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[PowerShell](/tag/powershell/)

Table of Contents

*   [Defining the Basic Write-Log Function](#defining-the-basic-write-log-function)
*   [Testing the Write-Log Function](#testing-the-write-log-function)
*   [Adding Flexibility with a Custom Log File Path](#adding-flexibility-with-a-custom-log-file-path)
*   [Enforcing the File Path with ValidateScript](#enforcing-the-file-path-with-validatescript)
*   [Testing Write-Log Functionality and Validations](#testing-write-log-functionality-and-validations)
*   [Conclusion](#conclusion)

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`.

```powershell
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:

```powershell
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:

```powershell
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:

```powershell
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:

```powershell
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.

```powershell
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:

```powershell
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.

```powershell
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:

```powershell
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:

```powershell
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:

```powershell
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.

```powershell
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:

```powershell
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**](https://adamtheautomator.com/powershell-parameter/) tutorial and go deeper into function parameters!

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-function-parameters%2F&text=PowerShell%20Function%20Parameters%3A%20A%20Practical%20Guide%20to%20Building%20Better%20Functions)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-function-parameters%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-function-parameters%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2026/06/26995-troubleshoot-dns-issues-powershell-codex.webp)

### [Troubleshoot DNS Issues with PowerShell](/troubleshoot-dns-issues-powershell/)

Troubleshoot DNS issues with PowerShell by testing name resolution, DNS client settings, cache entries, and network connectivity in a repeatable workflow.

![](https://adamtheautomator.com/wp-content/uploads/2025/10/image_2025-10-24_095322075.png)

### [Migrating from PowerShell 6 to 7.5: Breaking Changes/New Features](/migrating-powershell-6-to-7-5/)

Migrate from PowerShell Core 6 to 7.5: breaking changes, features, and testing tips.

![](https://adamtheautomator.com/wp-content/uploads/2025/06/featured-image-6.png)

### [How to Add Timeouts to Pester Tests with PowerShell Runspaces](/pester-test-timeout-runspaces/)

Prevent Pester tests from hanging indefinitely using PowerShell runspaces. Learn to handle variable scoping, module loading, TestDrive access, and stream capture challenges with timeout protection.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
