Better PoSH: Using $PSDefaultParameterValues
Today's quick PoSH tip comes from a conversation I had with Kevin Crouch (@PsychoData) and Brett Miller (@BrettMiller_IT), and I got to learn about the $PSDefaultParameterValues variable, which I'd never used before.
$PSDefaultParameterValue allows you to define ahead of your functions how certain parameters should be answered. A great use case is when using Active Directly cmdlets to ensure that multiple calls to Domain Controllers always use the same one. Instead of a drawn out explanation about how it's used, I think a few lines of code will draw a better picture.
Because I'm using
-AD, this is going to apply to all CmdLets that match this (e.g.
1$PSDefaultParameterValues["*-AD*:Server"] = "MyFastDC" 2$PSDefaultParameterValues["*-AD*:Properties"] = "OperatingSystem" 3 4# Because I don't define SERVER here, but I have defined it above, the -SERVER parameter is populated automatically with "MyFastDC". Same for -PROPERTIES. 5Get-ADComputer $env:COMPUTERNAME 6 7# Because I define SERVER here, it takes presidence over the default defined above. The -PROPERTIES is still populated with OperatingSystem as above. 8Get-ADComputer $env:ComputerName -Server "MySlowDC" 9 10# Because I define PROPERTIES here, it takes presidence over the default defined above. The -PROPERTIES is now just LastLogonDate -- OperatingSystem will no longer be there. 11Get-ADComputer $env:ComputerName -Properties LastLogonDate 12 13# Because I define SERVER above but not here, it'll use the default server from above. There is no PROPERTIES parameter for New-AdComputer, so it's ignored. 14New-ADComputer -Name "SOMENEWCOMPUTER"