【问题标题】:Arguments in Powershell are not evaluated correctlyPowershell 中的参数未正确评估
【发布时间】:2016-05-21 22:34:37
【问题描述】:

powershell 中的参数没有像我期望的那样得到评估。 如果参数类型是对象或字符串,则将作为参数的数学表达式转换为字符串。

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

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

在语言规范中明确指出,如果参数是对象类型,则值将按原样传递,不进行强制转换。

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

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

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    此链接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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 2011-08-04
      • 1970-01-01
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多