【发布时间】:2015-07-01 15:51:27
【问题描述】:
我是 Power Shell 脚本的新手。 我正在尝试实现一个功能,该功能应该接受来自以下标准的用户输入
- 只有数字
- 范围在 1 到 15 之间
- 应接受以逗号分隔的数组字符串,例如:1、2、3、4、14、15
- 逗号之间可以包含空格
- 值不应重复
- 返回值必须是数组
到目前为止,我已经尝试过
Function Validate-Choice{
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory=$True)]
[ValidateRange(1,15)]
[string[]]$Item
)
Process {$Item}
}
Validate-Choice 1,2,3,4,5,6,7,8,9,10,11,13 # Similar Way i want O/p
Out Put:
1
2
3
4
5
6
7
8
9
10
11
13
$ReadInput = Read-Host -prompt "Please Choose from the list [1/2/3/4/5/6/7/8/9/10/11/12/13/14] You can select multiple Values EX: 1, 2, 3 -- "
$userchoices = Validate-Choice -item $ReadInput
$userchoices
If read the same input from Host Getting Below Error
Validate-Choice : Cannot validate argument on parameter 'Item'. The argument cannot be validated because
its type "String" is not the same type (Int32) as the maximum and minimum limits of the parameter. Make sure the argument is of type Int32 and then try the command again. At line:10 char:21
+ Validate-Choice '1,2,3,4,5,6,7,8,9,10,11,13'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Validate-Choice], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Validate-Choice
我也在尝试不同的正则表达式模式。但是失败了
Function Test-Something {
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory=$True)]
[ValidatePattern('(?:\s*\d{1,15}[1-15]\s*(?:,|$))+$')]
[string[]]$Item
)
Process { $Item }
}
上述函数是部分生成的。 任何人都可以在这里帮助我..!?
【问题讨论】:
-
\d{1,15}表示长度在 1 到 15 位之间的数字。[1-15]不是你可以做的数字 1-15([1-9]|1[0-5])。[]是特定字符或单个字符范围的字符类。例如,a-z适用于小写字母字符,0-9适用于数字 0 到 9。对于9及更高版本,您需要添加+或添加条件(也适用于小数)。 -
谢谢..!克里斯85。您能否提供完整的正则表达式模式来做到这一点?
-
我没有 powershell,所以无法测试。我可以编写一个我认为可行的正则表达式。
标签: regex powershell