Thursday, January 21, 2016

Setting default parameters for cmdlets without changing them with $PSDefaultParameterValues

I ran across something again recently that I find to be really cool. You can add a command to your profile to add default parameters to any cmdlet. I first saw this as a way to have Format-Table execute with the –AutoSize flag every time.


That is a cool idea if you are stuck on Powershell 4 or older. Now that Powershell 5 kind of does that already, I really didn’t think much about it. Sometime later, I found myself wanting to share a cmdlet with someone and the default parameter values were specific to the way I used it. I didn’t really like that so I changed it. I made it into a better tool.

Except now I was supplying those values over and over every time I used it for myself. I decided there had to be a better way and that’s when I finally remembered this trick. And it can work on any cmdlet.


So now I can keep my cmdlets more generic and still get the benefit of default parameters that benefit myself. I can stick in common server names or credentials. Any value that I can think of really. Just add it to my profile and I am all set.


Matt McNabb said...

I completely abuse $PSDefaultParameterValues for my day-to-day stuff! It makes life so much easier!

Another great use is in scripts and modules - you can set default values at the top of a script or in a module file. You can then change them later or even conditionally which is a nice feature.

One example is in scripts I write to manage AD objects. I can do something like:

$PSDefaultParameterValues = @{
'*-AD*:Server' = 'DC1'

Which tells all the AD cmdlets to use a single DC for all operations. Pretty sweet!

Mike Shepard said...

The main reason I don't do this is I can see myself forgetting that I set a default value this way and be confused when my script runs differently somewhere else.