Maybe I'm looking at this all wrong. But, I have a PowerShell function that I would like to test for the presence of an input parameter much like a switch. If the parameter is present, simply use/assign it a default value. Additionally, I would like for the user to be able to override the default and specify their own value. I can get it to work with some but not all of the above criteria with the following...
Function test {
[CmdletBinding()]
Param (
[Parameter(Mandatory=$false)]
[ValidateRange(1,25)]
[Int]
$OptionalNumber = 1
)
if($PSBoundParameters.keys -contains "OptionalNumber"){
Write-Output "The optional number parameter is present"
Write-Output "The Optional Number is: $OptionalNumber"
}else{Write-Output "The optional number parameter was not specified"}
}
Running "Test" works.
Running "Test -OptionalNumber 3" works.
Running "Test -OptionalNumber" fails.
I want to be able to use the "-OptionalNumber" and essentially use it as a switch without having to explicitly passing in the default value of 1 as specifying the value defeats the purpose of a default value.
I've tried various combinations of [ValidationScript()], [AllowNull()], [Nullable[int]] and a few others to no avail. I know I could break it up into two parameters, one as the switch and the other as a value... [Switch]$OptionalNumber and [Int]$OptionalNumberValue for instance. But that seems very clunky. I feel like there is a better/cleaner way.
EDIT: As suggested, I opened a feature request for this functionality to be added to PowerShell. https://github.com/PowerShell/PowerShell/issues/12104