Powershell ignores expression after function call

The following is a powershell script article:

function PickANumber() { 12 } function GetTheAnswer() { PickANumber + 30 } $answer = GetTheAnswer write-output "The answer is $answer" 

The output of this script:

 The answer is 12 

As far as I suppose, this is due to the fact that calls to powershell functions do not have brackets around the arguments or commas between them, so PickANumber + 30 parsed as PickANumber('+', 1) instead of PickANumber() + 1 . And this is not a mistake, unused arguments are simply ignored (for example, using JavaScript).

If you change it a little, then the answer will be 42:

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

But of course, is there a way to do this on one line?

I am posting here because it will also bite someone else.

+6
source share
2 answers

To avoid this trap, you can define your functions as follows

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

When executing PickANumber + 30 you will receive an error message

PickANumber: it is not possible to determine a positional parameter that takes the argument '+'.

+3
source

Right call

 (PickANumber) + 30 

The source code of PickANumber + 30 means calling PickANumber with two arguments + and 30 , which are simply ignored by PickANumber .

+8
source

Source: https://habr.com/ru/post/944810/


All Articles