2

Arguments in powershell don't get evaluated as I expect them. A mathematical expression as argument is casted to a string if the parameter type is object or string.

  • Powershell code: write-host 1+1
  • Result printed on screen: 1+1
  • Expected result: 2

Could somebody tell me why does this happen? What is the logic behind this behavior?

In the language specification it clearly states that if the parameter is of type object then the value will be passed as is with no casting.

Could you please point me to the language specification that describes this behavior as I could not find it.

Note: any function that accepts an object or a string will suffer from the same behavior.

1 Answer 1

3

this link here

When processing a command, the Windows PowerShell parser operates in expression mode or in argument mode:

    - 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.