user
user

Reputation: 23

In PowerShell 2.0, how do you prompt the user again if this error occurs?

I am working on a script that prompts the user to input the price of a book.
So far I have this:

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

It works if you put in a number, but the problem is that if you put in a letter, it will display

"Cannot convert value "5t" to type "System.Decimal". Error: "Input string was not in a correct format." At line:1 char:20 + [Decimal]$BookPrice <<<< = Read-Host "Enter the price of the book" + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId : RuntimeException"

And it will stop working.
What I want to do is instead of giving the user this error, prompt them to input numbers only. How can I achieve that?

Upvotes: 0

Views: 1420

Answers (1)

Vasili Syrakis
Vasili Syrakis

Reputation: 9601

You could use regex to replace any non-number characters:

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

Alternatively you would have to check the input with logic:

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

By the way, I added a . into the character class, in case you wanted to match floating point numbers. Otherwise you should change that character class to [^0-9] instead.

Upvotes: 1

Related Questions