我正在尝试编写一个powershell脚本,要求用户输入4位数的pin,如果数字不等于4,则发出警告。
这是我的,但它似乎不工作…
[int]$userPin = read-host 'type in your user pin'
if ($userPin.length -ne 4) {
write-host "Error, Pin must be 4 numbers"
}
这段代码无论如何都会写错误消息…任何帮助都是感激的!谢谢!
$userPin = while ($true) {
$entered = Read-Host 'type in your user pin'
if ($entered.Trim() -match '^d{4}$') { [int] $entered; break }
Write-Warning "$entered is not a 4-digit number; please try again."
}
上面一直提示,直到输入4位数字,并将其作为[int]
实例存储在变量$userPin
中。
注意,使用正则表达式匹配运算符-match
,首先使用正则表达式匹配,以确保准确输入4个十进制数字(d{4}
)[1]。这样,可以预先排除输入非数字,而不会导致直接将非数字的值强制转换为[int]
时出现的错误。
至于你试过的:
通过类型约束您的$userPin
变量为类型[int]
([int] $userPin = ...
),您强制其值-初始值和稍后分配的任何值-为该类型,并且[int]
(System.Int32
)的实例没有.Length
属性(而Read-Host
返回的原始[string]
实例有)。
默认情况下,PowerShell忽略尝试访问不存在的属性并返回$null
,因此您的$userPin.length -ne 4
条件相当于$null -ne 4
,它总是为真。
[1]严格地说,d
不仅匹配ascii范围内的十进制数字0
到9
,还匹配其他分类为数字的Unicode字符。为了消除歧义,您可以使用[0-9]
,尽管在实践中可能很少需要。
我对mklement0的出色回答的看法,同样的概念,继续问,直到用户的输入是4位数。
$inputBlock = {
try
{
[validatescript({[regex]::Match($_,'^d{4}$').Length -eq 4})]
$UserInput = Read-Host 'Type in your user PIN'
$UserInput
}
catch
{
Write-Warning "Error, PIN must be 4 numbers"
& $inputBlock
}
}
$userInput = & $inputBlock