James Brundage posted a blog entry How To Write a Console Application in PowerShell with Add-Type which used a here-string. One user (lcr) copied and pasted the text and got the following error:
Unrecognized token in source text.
At line:1 char:72
+ Add-Type -OutputType ConsoleApplication -OutputAssembly HelloWorld.exe <
+ CategoryInfo : ParserError: (:) , ParentContainsErrorReco
+ FullyQualifiedErrorId : UnrecognizedToken
I did the same thing and pasted into the console window and got the same error. That seemed strange so I brought up PowerShell_ISE and pasted into a new buffer and the problem was immediately clear. This is what I saw:
Notice that the Here-String is BLACK. It should be in BROWN. This almost always means that you have an extra space after the @” . Here is what the About_quoting_rules says about Here-Strings:
A here-string has the following format, where <Enter> represents
the linefeed or newline hidden character that is added when you press
the <Enter> key.
<string> [string] …<Enter>
– or –
<string> [string] …<Enter>
In either format, the closing quote must be the first character
on the line.
My guess is that the blogging software (or the browser) probably put an extra space after the “ when James wrote the entry. I checked and it did have an extra space. I deleted that character and the display changed to (notice that the here-string is brown):
This is one of the benefits of the syntax coloring in PowerShell_Ise. We think we know what it is we are looking at when we see it but the syntax coloring tells us what the truth is. You should take a few minutes to stop and really see what the syntax coloring is doing and what colors mean what. Then take your script and deliberately start breaking it with things like extra parenthesis, curly braces, quotes, misspelled tokens etc etc and what how the syntax coloring DOES or DOES NOT show these mistakes. Really spend some time on this to understand it so that when you brings thing up in the ISE – the coloring becomes a true diagnostic tool for you. What I think you’ll find is that the syntax highlighting does not always highlight the problem (that is what you are looking to see – when does it help you and when doesn’t it). After you break something, you should save the file and try to run it so that you also see the runtime error and learn how to map those errors back to fixes (it will be easy because you just broke it.)
Spend some time on these issues now so that you have the skills to efficiently deal with problems when time matters.
Jeffrey Snover [MSFT]
Windows Management Partner 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