Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to declare a class in a '.ps1' file?

Tags:

powershell

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

like image 535
Ralf_Reddings Avatar asked Oct 15 '25 19:10

Ralf_Reddings


1 Answers

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.

like image 59
Santiago Squarzon Avatar answered Oct 18 '25 13:10

Santiago Squarzon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!