Quote or not quote

Can you tell the difference between ? No?
Or maybe between ? Or between  or ?
Well I can’t. At least when simply looking at it. If you have ever copied code in Documents certainly know this issue.
Word (as well as other word processors) has an autocorrect feature to make quotes and a like looking more nicely.
When you copy code from the command prompt to word, nothing changes. As soon as you start typing in that code after any of the above characters or changing formats, Word is applying this autocorrect feature and changes the characters. If you now copy that code back into command prompt, it will be displayed again using a more simple character set, BUT they remain the original, autocorrected characters.
You can try this by yourself. Type the following command in your PowerShell window:

[PS] Scripts:> [int][char]’"’

The result should be 34.
Now, do the same with this line

[PS] Scripts:> [int][char]’“’

This time the result would be 8220 as double quote ” was replaced with this character: “. But you cann’t see the difference in the command window.
Important: The last line containing ‘@ needs to start at the very beginning of the line. Otherwise its not recognized to close @’

[PS] Scripts:> $SpecialChars = @’
"“”„“`‘’‚’-–
‘@

[PS] Scripts:> [char[]] $SpecialChars | ForEach-Object -begin {"Char`tHEX`tINT`n"} -Process{ "$_`t0x{0:x}`t{0}" -f [int]$_ }
Char HEX INT

" 0x22 34
" 0x201c 8220
" 0x201d 8221
, 0x201e 8222
` 0x60 96
` 0x2018 8216
‘ 0x2019 8217
, 0x201a 8218
‘ 0x27 39
– 0x2d 45
– 0x2013 8211
– 0x2013 8211
[PS] Scripts:>
[PS] Scripts:>

There are various workarounds. You could never change any copied code in Word or any similar word processor and of course never change formatting after pasting. But that will probably never happen.
You can press CRTL+Z directly after typing any of the above characters. This will revert the autocorrected characters back to the original one.
Or you can do some regex-ing after pasting code from Word or a blog post into a script.

[string]$path = ".MyPastedScript.ps1"

( Get-Content ]$path) | %{
# replace double quotes
$_ -replace "(u201c|u201d|u201e)",[char]34
} | %{
# replace single quotes
$_ -replace "(u2018|u2019)",[char]39
} | %{
# replace dash
$_ -replace "(u2013)",[char]45
} | %{
# replace tab with four spaces
$_ -replace "`t",(" " * 4)
} |
Set-Content $path

You can download the code from PoshCode.org
http://poshcode.org/3816
I hope next time you copy a script from a blog with “nicely” formatted quotes you can fix the script a bit fast than before.

Enjoy

Patrick Sczepanski ist seit 11 Jahren im Bann der IT Industrie. Er hat schon für Kunden verschiedenster Grössen gearbeitet (von unter 200 bis über 200.000 Mitarbeitern). Bei der redtoo ist er, als Senior Consultant, Experte für den Bereich Infrastructure Services.