如何使 Validate-set 也适用于强制参数输入提示? [英] How can I make Validate-set also to work for mandatory parameter input prompt?

查看:46
本文介绍了如何使 Validate-set 也适用于强制参数输入提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的函数使用动态验证集来获取强制参数.

I use dynamic validate sets for my functions for mandatory parameters.

如果未提供 Powershell 提示并强制用户输入.

When not provided Powershell prompts and forces user to input.

但是在这种情况下,TAB 没有响应,我必须输入值.

However in this case, TAB does not respond and I have to type the value.

有没有办法让动态验证集在提示时可用?

Is there a way to make dynamic validate set to be available on the prompt?

推荐答案

无能为力!

原因是主机应用程序向您显示的提示没有可用于循环访问有效值的必要信息.

There's nothing you can do!

The reason is that the prompt presented to you by the host application does not have the necessary information available to cycle through valid values.

要了解原因,必须准确了解在调用 cmdlet 而不将参数传递给 Mandatory 参数时会发生什么.一起探索吧!

To understand why, it's essential to understand exactly what happens when you invoke a cmdlet without passing an argument to a Mandatory parameter. Let's explore!

首先,让我们定义一个简单的示例函数:

First, let's define a simple sample function:

function Test-ValidateSet {
  param(
    [Parameter(Mandatory)]
    [ValidateSet('a','b','c')]
    [string[]]$Character
  )

  Write-Host "You entered: $Character!"
}

如果您想在按 Enter 键时查看 PowerShell 对语句执行的操作,请使用 Trace-Command.

If you want to see what PowerShell does to a statement when you hit enter, use Trace-Command.

PS C:\> Trace-Command ParameterBinding {Test-ValidateSet} -PSHost
DEBUG: ParameterBinding Information: 0 : BIND NAMED cmd line args [Test-ValidateSet]
DEBUG: ParameterBinding Information: 0 : BIND POSITIONAL cmd line args [Test-ValidateSet]
DEBUG: ParameterBinding Information: 0 : MANDATORY PARAMETER CHECK on cmdlet [Test-ValidateSet]
DEBUG: ParameterBinding Information: 0 :     PROMPTING for missing mandatory parameters using the host
cmdlet Test-ValidateSet at command pipeline position 1
Supply values for the following parameters:
Character[0]:

这些 DEBUG 消息必须是从调用提示的地方发出的.在 PowerShell GitHub 存储库中搜索使用主机提示缺少必需参数"将引导您 到此调用站点.

These DEBUG messages must have been emitted from where the prompt is being called. Searching through the PowerShell GitHub repo for "PROMPTING for missing mandatory parameters using the host" will lead you to this call site.

正如你可能破译的那样,Prompt() 方法只需要三件事:

As you may be able to decipher, the Prompt() method takes just 3 things:

  1. 标题([string])
  2. 一条消息([string])
  3. 一组描述([System.Management.Automation.Host.FieldDescription[]])

查看 FieldDescription 对象,你会发现它们大致对应于 [Parameter] 属性 - 没有其他类型的属性 - 那就是基本上为什么你不能基于验证属性来完成值.

Looking at the properties of a FieldDescription object, you'll find that they roughly correspond to the [Parameter] attribute - no other kind of attribute - and that's basically why you can't tab complete the values based on validation attributes.

这篇关于如何使 Validate-set 也适用于强制参数输入提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆