1

I'm not to sure this is possible, but I would like to try it out.

This is the basics of what I am trying to do:

function somefunction () {
    $ListOfItems = (get-childitem c:\).name
    param (
        [validateset($ListOfItems)][string]$Moo
    )
}

I don't know if a variable can be used in validateset or not. It doesn't look so. If it can be, how would I go about doing this?

6
  • That's not how validation works. Commented Jun 1, 2017 at 13:09
  • I normally place names of servers and such with "Name". However, I am trying to make it as easy for my end user as possible. Having options inside the script is the thing he is used to. But There are over 100 printers across 30 servers. I wanted to set each server as a validation set and only have those printers from that server on that validation stack. I also wanted it to be self-updating so I don't have to rewrite it. Commented Jun 1, 2017 at 13:14
  • 1
    Validation is for enforcing that parameters have values matching a list that you control. It's not intended for validating printer names (that may change at any given time) against a list of printers (that may change at any given time). You'd still do that kind of check in the function body. Commented Jun 1, 2017 at 13:28
  • 1
    @David I think you might be looking for an argument completer or a dynamicparam block Commented Jun 1, 2017 at 13:43
  • The simplest workaround is to get the list of items in the function and throw an error if the parameter's value doesn't match one of them, as @AnsgarWiechers suggested. Commented Jun 1, 2017 at 16:54

2 Answers 2

1

This is doable. You're after ValidateScript

Function somefunction () {
    param (
        [ValidateScript({$_ -in (Get-Childitem C:\).Name})] 
        [string]$Moo
    )
}

Edit
The default error for ValidateScript is not user friendly:

PS C:\> somefunction -Moo thing

somefunction : Cannot validate argument on parameter 'Moo'. The "$_ -in (Get-Childitem C:).Name" validation script for the argument with value "thing" did not return a result of True. Determine why the validation script failed, and then try the command again.

This StackOverflow post goes over how to generate custom error messages

Sign up to request clarification or add additional context in comments.

Comments

0

After reading the comments and completing researched based on the comments, I believe there is no simple way of doing what I want it to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.