Using Default Parameter Values

by May 9, 2013

If you find yourself submitting the same value for a cmdlet parameter over and over again, then PowerShell 3.0 lets you set a default value.

Once you defined a default value for a parameter, you no longer need to specify it. This can be very convenient in production scenarios. It can be dangerous, too, because scripts that rely on this may not run on other machines anymore.

For example, to default the Path parameter of Get-ChildItem to the temporary folder, this is what you do:

$PSDefaultParameterValues.Add('Get-ChildItem:Path', $env:temp)

Next time you run Get-ChildItem (or one of its aliases such as dir) without specifying a path, you get the content of your temp folder.

To make a default that is not limited to Get-ChildItem but applies to any cmdlet that has a Path parameter, replace the cmdlet name with a wildcard:

$PSDefaultParameterValues.Add('*:Path', $env:temp)

Once you play with this, you'll soon find that defaults can be very useful but should be limited to cmdlets where they make sense. Fortunately, $PSDefaultParameterValues will forget all values once you restart PowerShell, so it's easy to get rid of unwanted defaults.

Defaults you found useful should be defined in one of your profile scripts (for example, the one specified in $profile).

Twitter This Tip! ReTweet this Tip!