Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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)
123PS 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
- Anonymous
September 04, 2006
This is showing the differences between COMMAND vs EXPRESSION modes of the parser. Check out:
http://blogs.msdn.com/powershell/archive/2006/07/23/Issues_with_Windows_PowerShell_syntax.aspx
for details.
Cheers!
Jeffrey Snover [MSFT]
Windows PowerShell/Aspen Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx