PSDefaultParameterValues

Let's examine the first dictionary, PSDefaultParameterValues, in the following code sample:

# The automatic variable is great to set defaults
$labFolder = mkdir .StagingDirectory -Force
$PSDefaultParameterValues = @{
'*:Path' = $labFolder.FullName # Extremely generic. Set all Path parameters for all Cmdlets
'New-Item:ItemType' = 'File'
}

# Notice how all cmdlets use Path
# New-Item uses ItemType File now
New-Item -Name someFile
Get-ChildItem
Test-Path
Join-Path -ChildPath SomePath
Get-Item
New-FileCatalog -CatalogFilePath here.cat

# Cmdlets can still override defaults
Add-Content -Path (Join-Path -ChildPath someFile) -Value 'Some data'

# Clear the defaults or remove single keys
$PSDefaultParameterValues.Remove('*:Path')
$PSDefaultParameterValues.Clear()

As you can see, it is very easy to use this dictionary to store default values for an entire session or for an entire script run. In our sample, we used the parameter value for Path as a default for all cmdlets that have been called. But the same principle applies to other cmdlets as well. The great thing about this, as opposed to splatting, is that you can still override parameter values, which would have generated a parameter binding exception with splatting.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset