I want to provide a list of allowed names to the name
parameter, so that the user can tab
into them.
I have come up with the following:
Param(
[ValidateSet([foo])]
[string]$Name
)
$name
Class foo : System.Management.Automation.IValidateSetValuesGenerator{
[string[]] GetValidValues(){
return [string[]] ("cat", "dog", "fish")
}}
Typing .\myScript.ps1 -name
and then pressing tab
nothing is suggested. running .\myScript.ps1
returns an error:
Line |
3 | [ValidateSet([foo])]
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Unable to find type [foo].
I can do this exact set up in a psm1
file or just as a standard function and it works. I thought of moving the class into the top of the script file but this not allowed due to param()
needing to be the first line.
Is there a way around this issue? Am on pwsh 7.4
There is no workaround for what you're attempting: A PowerShell script with parameters that makes use of the ValidateSetAttribute(Type valuesGeneratorType)
overload which also defines the IValidateSetValuesGenerator
inheriting type in the same file.
You can either define a function in the script and dot source it:
class foo : System.Management.Automation.IValidateSetValuesGenerator {
[string[]] GetValidValues() {
return [string[]] ('cat', 'dog', 'fish')
}
}
function Get-Foo {
Param(
[ValidateSet([foo])]
[string]$Name
)
}
Use the ValidateSetAttribute(params string[] validValues)
overload for runtime evaluation:
Param(
[ValidateSet('cat', 'dog', 'fish')]
[string]$Name
)
Dot source the IValidateSetValuesGenerator
inheriting class before calling the script:
PS ..\pwsh> . .\FooValidatorClass.ps1
PS ..\pwsh> .\myFooScript.ps1 <TAB>
Or use a module as you already know.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With