How to use expressions as function parameters in powershell

This is a very simple task in every language I have ever used, but I cannot figure it out in PowerShell. An example of what I'm talking about in C:

abs(x + y)

The expression x + yis evaluated, and the result is passed absas a parameter ... how to do it in PowerShell? The only way I have guessed so far is to create a temporary variable to hold the result of the expression and pass this.

PowerShell seems to have very strange grammar and parsing rules that constantly catch me by surprise, just like this situation. Does anyone know the documentation or tutorial explaining the basic theory of language? I can’t believe that these are all special cases, there must be some kind of rhyme or reason that not a single textbook that I have yet to read explains. And yes, I read this question , and all these lessons are terrible. I was pretty much assigned to learning from existing code.

+3
source share
2 answers

In your case, simply surrounding the expression with a bracket allows you to pass it to your function.


, PowerShell .

, - , .

, . .

1+2          Expression mode - starts with number
"string"     Expression mode - starts with quote
string       Command mode - starts with letter
& "string"   Command mode - starts with &
. "string"   Command mode - starts with . and a space
.123         Expression mode - starts with . and number (without space)
.string      Command mode - starts with a . that is part of a command name

, .

, abs :

function Abs($value)
{
    Write-Host $args
    if($value -lt 0) { -$value } else { $value }
}

Abs 1 + 2
#Prints:  + 2
#Returns: 1

Abs 1+2
#Prints:  
#Returns: 1+2

Abs (1 + 2)
#Prints:  
#Returns: 3

Abs (1+2)
#Prints:  
#Returns: 3
+6

, , . , PowerShell:

PS> function abs($val) {Write-Host "`$val is $val"; if ($val -ge 0) {$val} `
                                                    else {-$val}}
PS> abs (3+4)
$val is 7
7

, Windows PowerShell ( ), ( ), , PowerShell 2.0.

PowerShell. № 10 PowerShell.

+3

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


All Articles