Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
Gaterde Avatar asked Mar 13 '26 16:03

Gaterde


2 Answers

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"
}
like image 128
Mathias R. Jessen Avatar answered Mar 16 '26 10:03

Mathias R. Jessen


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
like image 31
nimizen Avatar answered Mar 16 '26 08:03

nimizen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!