PowerShell Quiz

by Doug Finke on July 1, 2008

in PowerShell

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 }

1 Shankar 07.02.08 at 4:54 am

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..

2 Steven Murawski 07.02.08 at 7:44 am

My guess..
The second option returns a String object, while the other three are writing the string to the output stream.

3 Doug Finke 07.02.08 at 11:21 am

Sorry, try again.

4 Daniel Chait 07.02.08 at 11:25 am

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.

5 Doug Finke 07.02.08 at 1:03 pm

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.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>