wasif
wasif

Reputation: 15488

Powershell calculator script is not working properly

I have created a very simple powershell script to calculate expressions. That is:

$expression = read-host -prompt "Enter an expression"
$result = $expression
write-host "The result is $result"
read-host

However, when I use it like this:

Enter an expression: 2+3

The result is 2+3

How can I make the 2nd line calculate the result?

Upvotes: 1

Views: 1188

Answers (1)

f6a4
f6a4

Reputation: 1782

Maybe this is helpful for you:

 $expression = read-host -prompt "Enter an expression"

# check for dangerous code
if( ($expression -replace '^[0-9\+\-\*\/ ]+$').Length -eq 0 ) {
    try {
        $result = Invoke-Expression $expression
        write-host "The result is $result"
    }
    catch {
        write-host "Syntax error"
    }
}
else {
    write-host "Invalid expression"
}

Upvotes: 3

Related Questions