PowerShell string escaping

Ok, this is probably a very very basic topic to tal about, but anyway…

String escaping has always been cumbersome and tricky in – I guess – most of the programming languages I have used. You need a way to represent special characters, most of the times you do this by defining them through an escape sequence, and most of the times the escape sequence is made up of an escape character followed by another character (or a character code). You know that \n stands for “newline” in ANSI C syntax, right?

PowerShell follows these widely adopted standards, with a couple of gotchas.

First off, the escape character is the backtick (`), which is 0x60 (96) ASCII code and the U+0060 Unicode code.

Which is fine, I mean, using a backslach or a backtick… it doesn’t matter.

Well, yes, it does’t matter, although I’m using the Italian keyboard layout and we have no grave accent (back tick) character anywhere. Sgrunf 🙁

Second: in PowerShell we can use both single quote and double quote characters to enclose string literals.

The difference stands in the way the string is interpreted before being used.

Consider, as an example, the MSSQL$SHAREPOINT string.

If you use single quotes (‘MSSQL$SHAREPOINT’), you get exactly what you have typed within the single quotes.

If you use double quotes, and try to print-out the string variable:

Write-Host “MSSQL$SHAREPOINT”

You get, guess what, just MSSQL on your output stream.

The reason for this behavior is due to the automatic variable substitution that the PowerShell intepreter performs and strings literals escaped by double quotes: variable names, in PowerShell, are prefixed by the $ char, which means that the previous string is resolved as MSSQL concatenated with the value of the SHAREPOINT variable, which in my case is just null.

Sometimes, even simple things get tricky!