I am working on a function with a normal string parameter, with a default values assigned, and 1 dynamic parameter. My goal is for the dynamic parameter to use the string value in the first parameter. The code works if I define the -Path parameter on the commandline, but it doesn’t seem to work with the default value. I have checked the $PSBoundParameters variable and it is empty when I call it in the dynamic parameter block. Does anyone have any advice for this? I want to provide a default location for my function, with the flexibility for the user to define their own path if desired. Thanks for any advice!
function Test-Function
{
[CmdletBinding()]
Param
(
# Param1 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string]$Path = 'C:\Temp\SubFolder1'
)
DynamicParam {
# Set the dynamic parameters' name
$ParameterName = 'FileName'
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $true
$ParameterAttribute.Position = 1
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
# Generate and set the ValidateSet
$arrSet = Get-ChildItem -Path $Path -File | select -ExpandProperty Name
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
}
Begin
{
# Bind the parameter to a friendly variable
$FileName = $PsBoundParameters[$ParameterName]
}
Process
{
$FileName
}
End
{
}
}