How can I get dynamic suggestions for user input in PowerShell without errors?

0
0
Asked By CuriousCoder42 On

I'm working with two PowerShell functions, `get-foo` and `new-foo`, that interact with a tree structure resource implemented through the file system. The `get-foo` function is performing well - it restricts user input to valid values from the structure. However, I'm having trouble with `new-foo`. I want it to suggest values from the tree just like `get-foo`, but also allow users to input any arbitrary values without throwing an error if the value doesn't exist. Right now, `new-foo` causes an error when a user enters a value that's not already in the tree structure. Here's part of my code:

```powershell
Function get-foo{
param(
[ValidateSet([myTree], ErrorMessage = "{0} Is not a valid structure")]
[string]$name
)
$name
}

Function new-foo{
param(
[ValidateSet([myTree])]
[string]$name
)
$name
}

Class myTree : System.Management.Automation.IValidateSetValuesGenerator{
[string[]] GetValidValues(){
return [string[]] (Get-ChildItem -path "C:temp" -Recurse | ForEach-Object {($_.FullName -replace 'c:\temp\')})
}
}
```

Both functions check a directory (`C:temp`) for valid names. I want `new-foo` to provide dynamic autocompletion without failing when a non-existent value is entered. I've checked the parameter attributes, but it seems like only `ValidateSet` applies. Any suggestions on how to achieve this? I'm using PowerShell 7.4.

2 Answers

Answered By TechieTim78 On

I'm curious about your custom validate set for `[colNames]`. Is it the same as `[myTree]`? It's a bit unclear how `new-foo` and `get-foo` are supposed to differ, since they seem to operate on the same structure. Could you clarify that?

CuriousCoder42 -

Ah, sorry about that! Both functions actually use `myTree`. I corrected my original post to clarify that.

Answered By HelpfulHarry99 On

You might want to look into using `Register-ArgumentCompleter`. This lets you create a custom completer that provides dynamic suggestions without requiring the values to be in a `ValidateSet`. It can be tailored to allow any user input. Check out the documentation [here](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/register-argumentcompleter?view=powershell-7.4).

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.