Reputation: 15488
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
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