使用变量作为运算符-Powershell [英] Use a variable as an operator - Powershell
本文介绍了使用变量作为运算符-Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从Powershell开始,并试图做一个简单的计算器.
I startet with Powershell and tried to do a simple calculator.
这就是我所拥有的:
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
但是我不能将$z
变量用作操作...
But I can't use the $z
variable as an operation...
有什么想法吗?
推荐答案
您可以使用Invoke-Expression
:
PS C:\> $x,$y,$op = '1.23','3.21','+'
PS C:\> Invoke-Expression "$x$op$y"
4.44
确保您验证输入:
Function Invoke-Arithmetic
{
param(
[float]$x,
[float]$y,
[ValidateSet('+','-','*','/')]
[string]$op
)
return Invoke-Expression "$x $op $y"
}
这篇关于使用变量作为运算符-Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文