Powershell中的参数未正确评估

时间:2016-02-11 08:40:48

标签: powershell powershell-v4.0

PowerShell中的参数不会像我期望的那样得到评估。 如果参数类型为object或string,则将数学表达式作为参数转换为字符串。

  • Powershell代码:write-host 1 + 1
  • 打印在屏幕上的结果:1 + 1
  • 预期结果:2

有人可以告诉我为什么会这样吗? 这种行为背后的逻辑是什么?

在语言规范中,它明确指出如果参数是object类型,那么该值将按原样传递而不进行转换。

请您指出描述此行为的语言规范,因为我找不到它。

注意任何接受对象或字符串的函数都会遭受同样的行为

1 个答案:

答案 0 :(得分:3)

此链接here

处理命令时,Windows PowerShell解析器会运行     在表达模式或参数模式中:

    - In expression mode, character string values must be contained in
      quotation marks. Numbers not enclosed in quotation marks are treated
      as numerical values (rather than as a series of characters). 

    - In argument mode, each value is treated as an expandable string 
      unless it begins with one of the following special characters: dollar
      sign ($), at sign (@), single quotation mark ('), double quotation
      mark ("), or an opening parenthesis (().


Example            Mode         Result
------------------ ----------   ----------------
2+2                Expression   4 (integer)
Write-Output 2+2   Argument     "2+2" (string)
Write-Output (2+2) Expression   4 (integer)
$a = 2+2           Expression   $a = 4 (integer)
Write-Output $a    Expression   4 (integer)
Write-Output $a/H  Argument     "4/H" (string)