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.
Essentially, $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. Get-ADComputer, New-ADComputer, Rename-ADObject)
$PSDefaultParameterValues["*-AD*:Server"] = "MyFastDC"
$PSDefaultParameterValues["*-AD*:Properties"] = "OperatingSystem"
# Because I don't define SERVER here, but I have defined it above, the -SERVER parameter is populated automatically with "MyFastDC". Same for -PROPERTIES.
# Because I define SERVER here, it takes presidence over the default defined above. The -PROPERTIES is still populated with OperatingSystem as above.
Get-ADComputer $env:ComputerName -Server "MySlowDC"
# 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.
Get-ADComputer $env:ComputerName -Properties LastLogonDate
# 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.
New-ADComputer -Name "SOMENEWCOMPUTER"