Поделиться через


in PowerShell, parameter binding is stronger than operators

This is one of the PowerShell behaviors that caught me a little off-guard at first.  I don't necessarily disagree with the choice the PS team made (although obviously, at least for me as a data point, it violated the principle of least surprise :), but since others may hit it as well, I wanted to toss a random blog entry up just in case.

I had written something like this in a script and had it throw an error that it took me a second to understand - the "-f" operator I was trying to use wasn't being parsed, in fact, as the -f operator at all, but instead as a cmdlet parameter (short for the -foregroundcolor param).

PS C:\> "{0}{1}{2}" -f (1,2,3)
123

PS C:\> write-host "{0}{1}{2}" -f (1,2,3)

Write-Host : Cannot convert 'System.Object[]' to the type 'System.ConsoleColor' required by parameter 'ForegroundColor'. Specified method is not supported.

At line:1 char:26

+ write-host "{0}{1}{2}" -f  <<<< (1,2,3)

The easiest way to get across the behavior is for me to compare it to a language that treats operators as higher precedence than parameter binding.  Python happens to be one of those.

Comparing ‘print’

PS C:\> write-host 1+1

1+1

PS C:\> write-host (1+1)

2

>>> print 1+1

2

>>> print (1+1)

2

Comparing operator vs. param binding precedence

PS C:\> function foo { "I got param $args" }

PS C:\> foo 1+1

I got param 1+1

>>> def foo(arg): print arg

...

>>> foo(1+1)

2

Comments