I am trying to use a dynamic parameter in PowerShell, but the value for the parameter doesn't seem to exist after I have run through my script.
[CmdletBinding()]
Param (
[Parameter(
Mandatory=$true,
Position=0,
HelpMessage = "The entity ID for the Version"
)]
[string]$TPVersionID,
[Parameter(
Mandatory=$true,
Position=1,
HelpMessage = ""
)]
[string]$VersionNumber,
[Parameter(
Mandatory=$true,
Position=2,
HelpMessage = "This is a boolean value; enter any value to make it True, leave it blank to make it False."
)]
[bool]$PullVersionDoc
)
function Get-VersionParam{
[CmdletBinding()]
Param ([string]$TPVersionID, [string]$VersionNumber, [bool]$PullVersionDoc?)
DynamicParam {
if ($PullVersionDoc) {
write-host("HEY!")
$attributes = new-object System.Management.Automation.ParameterAttribute
$attributes.Position = 3
$attributes.Mandatory = $true
$attributeCollection = new-object `
-Type System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($attributes)
$dynParam1 = new-object `
-Type System.Management.Automation.RuntimeDefinedParameter('VersionDocumentID', [Int32], $attributeCollection)
$paramDictionary = new-object `
-Type System.Management.Automation.RuntimeDefinedParameterDictionary
$paramDictionary.Add('VersionDocumentID', $dynParam1)
return $paramDictionary
}
}
}
Get-VersionParam
#Write-Host "Dynamic Parameter PullVersionDoc? = " $PullVersionDoc
Write-Host $PSBoundParameters
I want the script to ask for a [VersionDocumentID] if the boolean value for [PullVersionDoc] is TRUE to use later on in the script, but when I write out the [$PSBoundParameters] the parameter doesn't exist. How did I get the value so that I can use it?
$a = Get-VersionParam; Write-host $a[bool]parameter. Use[switch]instead. This way you add the param name to make Switch True or leave it off and it will evaluate to False. Also, you access$PSBoundParameters[$ParameterName]in the Begin block and work on items within the Process block.VersionDocumentIDparameter will only exist inside the function, unless you add something like$script:VersionDocumentID = $VersionDocumentIDto your function body (or outputs the value and store it like @4c74356b41 showed) . Your function doesn't do anything except ask for values it never uses.