PSBoundParameters

Another cool automatic variable, PSBoundParameters, gives you access to all parameters that were bound in your cmdlet or function. Do you remember the variable $args from before? This is $args on steroids. With it being a dictionary, we can access all bound parameters by their name; manipulate, add, and remove keys; and use this variable for splatting, as you can see in the following code sample:

# Another cool dictionary to use
function Get-AllTheThings
{
[CmdletBinding()]
param
(
$Parameter1,

$Parameter2
)

$PSBoundParameters | Out-Host
Get-AllTheInternalThings @PSBoundParameters
}

function Get-AllTheInternalThings
{
[CmdletBinding()]
param
(
$Parameter1,

$Parameter2
)

Write-Verbose -Message 'Pretty cool, eh?'
Write-Host "Parameter1 was $Parameter1 and Parameter2 was $Parameter2"
}

# Calling Get-AllTheThings will pass all possible parameters
# on to Get-AllTheInternalThings.
Get-AllTheThings -Parameter1 1 -Parameter2 2 -Verbose

# Be careful: If parameters do not exist, you still get errors
function Get-AllTheInternalThings
{
# Leave the parameter binding and all parameter attributes, and the bound
# parameters will not throw an error ;)
[CmdletBinding()]
param
(
$Parameter1
)
}
Get-AllTheThings -Parameter1 1 -Parameter2 2 -Verbose # Throws now...

We commonly use the bound parameters in scenarios where we write adapters or wrappers around functions. Take a look at the following abbreviated code sample from https://github.com/AutomatedLab/AutomatedLab.Common where this exact technique is used in the New-TfsAgentQueue cmdlecalling Get-TfsAgentQueue internally, using PSBoundParameters like you can see in the following code sample:

function New-TfsAgentQueue
{

param
(
[Parameter(Mandatory)]
[string]
$InstanceName,

[Parameter()]
[string]
$CollectionName = 'DefaultCollection',

[ValidateRange(1, 65535)]
[uint32]
$Port,

[string]
$ApiVersion = '3.0-preview.1',

[Parameter(Mandatory)]
[string]
$ProjectName,

[switch]
$UseSsl,

[string]
$QueueName,

[Parameter(Mandatory, ParameterSetName = 'Cred')]
[pscredential]
$Credential,

[Parameter(Mandatory, ParameterSetName = 'Pat')]
[string]
$PersonalAccessToken
)

$existingQueue = Get-TfsAgentQueue @PSBoundParameters
if ($existingQueue) { return $existingQueue }

# Things happen.
}
..................Content has been hidden....................

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