在PowerShell 2.0中,如果发生此错误,如何再次提示用户?

时间:2014-02-09 01:22:35

标签: powershell

我正在制作一个脚本,提示用户输入图书的价格 到目前为止,我有这个:

[Decimal]$BookPrice = Read-Host "Enter the price of the book"
$BookPriceRounded = "{0:C2}" -f $BookPrice

如果你输入一个数字就可以了,但问题是,如果你输入一个字母,它会显示

  

“无法将值”5t“转换为”System.Decimal“。错误:”输入字符串的格式不正确。“   在行:1 char:20   + [十进制] $ BookPrice<<<< =读取主机“输入书籍的价格”       + CategoryInfo:MetadataError:(:) [],ArgumentTransformationMetadataException       + FullyQualifiedErrorId:RuntimeException“

它会停止工作。
我想要做的不是给用户这个错误,而是提示他们只输入数字。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式替换任何非数字字符:

[Decimal]$BookPrice = Read-Host "Enter the price of the book"
$BookPriceRounded = "{0:C2}" -f ($BookPrice -replace '[^0-9\.]','')

或者你必须用逻辑检查输入:

Clear-Host 
$BookPrice = Read-Host "Enter the price of the book"

while ($BookPrice -NotMatch "[0-9]+(\.[0-9]+)?") {
    $BookPrice = Read-Host "Please enter a number or decimal only"
}

$BookPriceRounded = "{0:C2}" -f [Decimal]$BookPrice
Write-Host $Bookpricerounded

顺便说一下,我在字符类中添加了.,以防你想要匹配浮点数。否则,您应该将该字符类更改为[^0-9]

相关问题