Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell is ignoring expression after function call

Here is a powershell script:

function PickANumber()
{
  12
}

function GetTheAnswer()
{
  PickANumber + 30
}

$answer = GetTheAnswer
write-output "The answer is $answer"

The output of this script is:

The answer is 12

As far as I call guess, this happens because powershell function calls do not have brackets around the arguments or commas between them, so PickANumber + 30 is parsed as something like PickANumber('+', 1) instead of PickANumber() + 1. And this is not an error, the unused args are simply ignored (like with JavaScript).

If you change it slightly, then the answer is 42:

function GetTheAnswer()
{
  $a = PickANumber
  $a + 30
}

But surely there is a way of doing this on one line?

I'm posting here because this is going to bite someone else too.

like image 324
Anthony Avatar asked May 12 '13 11:05

Anthony


2 Answers

The correct call is

(PickANumber) + 30

The original code PickANumber + 30 means a call to PickANumber with two arguments + and 30 which are simply ignored by PickANumber.

like image 68
Roman Kuzmin Avatar answered Nov 14 '22 13:11

Roman Kuzmin


To avoid this pitfall you could define your functions like this

function PickANumber()
{
  [CmdletBinding()]
  param()

  12
}

When executing PickANumber + 30 you will get the error

PickANumber : A positional parameter cannot be found that accepts argument '+'.

like image 36
Lars Truijens Avatar answered Nov 14 '22 12:11

Lars Truijens