问题
I startet with Powershell and tried to do a simple calculator.
This is what I have:
Function ReturnRes ($x,$y,$z)
{
$res= [float] $z [float]$y
return $res
}
Write-Host $res
$var1 = Read-Host "Zahl1"
$var2 = Read-Host "Zahl2"
$op = Read-Host "Operator(+-*/)"
ReturnRes -x $var1 -y $var2 -z $op
But I can't use the $z
variable as an operation...
Any ideas?
回答1:
You can use Invoke-Expression
:
PS C:\> $x,$y,$op = '1.23','3.21','+'
PS C:\> Invoke-Expression "$x$op$y"
4.44
Make sure you validate the input:
Function Invoke-Arithmetic
{
param(
[float]$x,
[float]$y,
[ValidateSet('+','-','*','/')]
[string]$op
)
return Invoke-Expression "$x $op $y"
}
回答2:
Here's another solution, add a default case to the switch to handle non-valid operators:
Function ReturnRes($x,$y,$z){
switch($z){
"+" {[float]$x + [float]$y}
"-" {[float]$x - [float]$y}
"*" {[float]$x * [float]$y}
"/" {[float]$x / [float]$y}
}
}
Write-Host $res
$var1 = Read-Host "Zahl1"
$var2 = Read-Host "Zahl2"
$op = Read-Host "Operator(+-*/)"
ReturnRes -x $var1 -y $var2 -z $op
回答3:
You have to use Invoke-expression
cmdlet to do this kind of job.
This is what you need:
Function ReturnRes ($x,$y,$z)
{
$res= "[float]$x $z [float]$y"
iex $res
}
回答4:
If you want more flexibility (like the ability to support trig functions for example) you could do this:
$lookupFunction = @{"+"={$args[0]+$args[1]};
"-"={$args[0]-$args[1]};
"*"={$args[0]*$args[1]};
"/"={$args[0]/$args[1]};
"sin"={[math]::sin($args[0])}
}
Write-Host $res
$var1 = Read-Host "Zahl1"
$var2 = Read-Host "Zahl2"
$op = Read-Host "Operator(+ - * / sin)"
if ($lookupFunction.containsKey($op)) {
# $var2 is ignored in case of sin function
& $lookupFunction[$op] $var1 $var2
} else {
write-host Unsupported operator: $op
}
Besides being more flexible then invoke-expression, it also insulates the user from having to know that the sin function (for example) is accessed with this syntax [math]::sin(arg)
来源:https://stackoverflow.com/questions/34672567/use-a-variable-as-an-operator-powershell