为什么将true分配给变量it不会得出true?

时间:2019-10-09 06:47:17

标签: powershell boolean boolean-expression

$test = true
if($test) {
  Write-Output "true"
} else {
  Write-Output "false"
}

输出为“ false”,但是为什么呢?我为COM对象属性分配了truefalse,它似乎正常工作...我做错什么了吗?什么时候在PowerShell中使用true$true比较合适?

编辑:一些用户提到我应该看到一个错误,但我没有看到。我已经在PowerShell 2.0(Windows 7)和PowerShell 4.0(Windows 8.1)中进行了尝试。 truefalse确实像我说的那样更改COM属性。

编辑:事实证明,正在为true分配COM属性,但实际上它们是错误的。我们的程序中有gnuwin32程序,其中两个程序为true和false:

C:\gnuwin32\bin\true.EXE
C:\gnuwin32\bin\false.EXE

因此,在那些计算机上,类似$x = true的命令将运行命令C:\gnuwin32\bin\true.EXE,该命令没有输出,并且$x为空。没人能弄清楚,要设置为true的com属性实际上并不是那样设置的。

标记为正确的答案说明“真实”,并且该值实际上是一个空值,正是这帮助我弄清了这一点。

3 个答案:

答案 0 :(得分:3)

由于问题是为什么发生,让我在答案中深入研究


if($test)检查是否为 truthy 。基本上,它将表达式的结果转换为布尔值,然后检查其是对还是错。您可以了解有关此in that answer的更多信息。

在您的情况下,与Martin Brandl mentioned in his helpful answer一样,尝试分配$test = true(在大多数情况下)会导致异常,但代码将继续执行

  

注意粗体中的语句并不总是正确的,因为它取决于$ErrorActionPreferrence,但在您的情况下确实如此,因为您提到收到了输出

分配失败后,$test的值为$null-您可以通过以下方法进行检查:

$test -eq $null

$null为假值,因此您的if()中的表达式的值为$false,并且执行了else关键字之后的代码,因此您的False输出。

答案 1 :(得分:1)

您的第一行$test = true可能会引发以下异常(除非您的$ErrorActionPreference设置为 SilentlyContinue ):

true : The term 'true' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:9
+ $test = true
+         ~~~~
    + CategoryInfo          : ObjectNotFound: (true:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

如果您不想将$test设为值为1(true)的布尔值,则必须像这样分配它: $test = $true

为什么输出为“ false”?

如上所述,$test = true将引发异常,因此$test没有被声明/定义。我建议您将$ErrorActionPreference设置为 Continue Stop 来捕获这些类型的错误。

答案 2 :(得分:0)

Unix的“ true”和“ false”命令与powershell $ true和$ false不同。 Unix只能设置退出代码,但不输出。 powershell变量提供布尔输出。这是一种测试前一命令的退出代码的解决方法:

zip