Gaterde
Gaterde

Reputation: 819

Use a variable as an operator - Powershell

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?

Upvotes: 3

Views: 1822

Answers (4)

CB.
CB.

Reputation: 60938

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
}

Upvotes: 1

Χpẘ
Χpẘ

Reputation: 3451

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)

Upvotes: 0

nimizen
nimizen

Reputation: 3419

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

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

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"
}

Upvotes: 4

Related Questions