3

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?

techguy1029
  • 743
  • 10
  • 29
Gaterde
  • 779
  • 1
  • 7
  • 25

4 Answers4

4

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"
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
1

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
}
techguy1029
  • 743
  • 10
  • 29
CB.
  • 58,865
  • 9
  • 159
  • 159
1

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
nimizen
  • 3,345
  • 2
  • 23
  • 34
0

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)

Χpẘ
  • 3,403
  • 1
  • 13
  • 22