这应该很简单,但我做不到。我是PowerShell新手,所以我的错误可能是显而易见的。我试图使用while循环向用户请求输入,如果输入的内容不是数字,则提示用户再试一次。在bash中,它应该是这样的:
while read -p "What is the first number? " first; do
if [[ $first = *[[:digit:]]* ]]; then
break # if $first is numeric, break loop
else
echo "$first is not numeric. Enter a numeric value. "
fi
done下面是我对PS的看法:
While ($first = (Read-Host "What is the first number?") -as [double]) {
if ($first -eq $null) { Write-Host "Please enter a numeric value." }
else { break }
}在上面的例子中,当输入一个数字时,我可以很好地中断循环,但是如果我输入一个字符串,我就看不到Write-Host语句。
发布于 2018-11-19 00:18:35
查看While行:
While ($first = (Read-Host "What is the first number?") -as [double]) 这只会在输入已经是双倍时进入/继续循环体,因为它将转换为double作为循环条件的一部分。您希望在任何输入上输入循环体,然后只检查它是否为双变量。至少,bash代码就是这样做的:
While ($first = (Read-Host "What is the first number?")) {
if ( ($first -as [double]) -eq $null) { Write-Host "Please enter a numeric value." }
else { break }
}或者,可以通过否定整个表达式继续使用强制转换作为条件的一部分,从而避免对尴尬的break的需要。
While (-not ($first = (Read-Host "What is the first number?") -as [double])) {
Write-Host "Please enter a numeric value."
}https://stackoverflow.com/questions/53366707
复制相似问题