PowerShell-Technique: $PSDefaultParameterValues

Created March 26, 2023

Enhance Your PowerShell Scripting with Default Parameter Values

In this post, we'll take a closer look at the benefits of using default parameter values in PowerShell. As we previously explored in our discussion of splatting, setting default values for parameters in your commandlets or functions can make your scripts more efficient and easier to maintain.

To set default parameter values in PowerShell, you can use the $PSDefaultParameterValues preference variable. This allows you to define default values for parameters without having to specify them in the function call. For example, let's say we want to set default headers for an Invoke-RestMethod command. We can define a $headers object and then set the default headers for Invoke-RestMethod like this:

$headers = @{
        "Authorization" = "Bearer $($Token.access_token)"
        "Content-type"  = "application/json"
$PSDefaultParameterValues = @{
    "Invoke-RestMethod:Headers" = $Headers

Now, every time we use Invoke-RestMethod in our session, the headers parameter will be automatically filled with the $headers object we defined above.

One of the biggest advantages of using default parameter values over splatting is that you can easily override default values without changing them permanently. In a splat, you must change the values permanently, but with default parameter values, you can easily overwrite them as needed. For instance, you might want to switch out the $headers object for a different set of headers in a particular command call.

It's also worth noting that you can define default parameter values for multiple functions or commandlets in the same hashtable, as well as use wildcards for the property name, which is always a combination of the function or commandlet name and the parameter name. For example:

$PSDefaultParameterValues = @{
    "Invoke-*:Headers" = $Headers

This sets the default Headers value for all cmdlets with a name that starts with "Invoke".

While default parameter values can simplify your code, it's important to be cautious when using wildcards in the $PSDefaultParameterValues hashtable. It can be tricky to predict how wildcard matches will affect other cmdlets or functions.

Another thing to keep in mind is that when working on larger projects with multiple collaborators, default parameter values defined by one person may not be well-documented or understood by others. This can lead to confusion and bugs down the line.

In summary, using default parameter values can make your PowerShell scripting more efficient and streamlined. Just be mindful of the potential risks and communicate clearly with your team when using this technique.

Thats all for now.

If you have any thoughts or feedback on this topic, feel free to share them with me on Twitter at Christian Ritter. Best regards,