PowerShell IF语句变量

时间:2015-04-16 17:48:58

标签: powershell

我很好奇如何在我的代码中进一步使用IF语句逻辑。让我详细说明一下。

$a=1
$b=10000
    if(($a=1) -or ($b=1))
       {write-host ""}  #Here, I want to write what ever variable was $true
                        #in the if statement above.... so I want it to 
                        #write "1" which was $a and was $true in the if
                        #statement...

我可以写更多的逻辑来实现这一点,但我想知道if语句使用的值是否可以在代码中再次使用。我觉得有一个“隐藏”变量可能吗?

1 个答案:

答案 0 :(得分:1)

($a=1)通常是一个赋值语句。在Powershell中并非如此,但它确实看起来像一个bug。 Powershell进行比较的方法是使用-eq。所以,

if(($a -eq 1) -or ($b -eq1))

现在,简单的解决方案有点不同。如果$a$b恰好是1,会发生什么?

$comp = 1 # Value to compare against
$a=1
$b=100
if($a -eq $comp) { write-host "`$a: $a" }
if($b -eq $comp) { write-host "`$b: $b" }

这种方法很容易理解,在大多数情况下比速度等其他因素更重要。

相关问题