1..10 | % {write-host "hello $_"} 1..10 | % {"hello " + $_} 1..10 | % {write-host "hello " + $_} 1..10 | % {write-host "hello $($_)"}
Three of these print the same result, which one doesn’t?
Researching the optimal; implementing the practical
1..10 | % {write-host "hello $_"} 1..10 | % {"hello " + $_} 1..10 | % {write-host "hello " + $_} 1..10 | % {write-host "hello $($_)"}
Three of these print the same result, which one doesn’t?
{ 5 comments… read them below or add one }
This is so surprising.. I am not a Windows programmer but have been doing scripting perl for a while and this just bet the whole out of me..
I think I would want to learn about PowerShell after this quiz..
very nice..
My guess..
The second option returns a String object, while the other three are writing the string to the output stream.
Sorry, try again.
Write-host takes a (space delimited) list of arguments and writes them out.
Sending it three strings, “hello “, +, and 1, it will dutifully print out all three of them.
Very sneaky Doug.
Correct.
Yet, in the heat of the battle, when a script causes unexepected results, the syntax looks like what you’d expect.
This demonstrates some PowerShellisms. Parameter Binding, embedding variables in string and their replacement.
In a follow up, I’ll show how this causes unexpected non terminating errors.