PowerShell Best Practice #1 – Use Single Quotes

I’m going to kick off this series with a no-brainer.

In PowerShell, there are 2 ways to quote strings, using single-quotes (‘) or double-quotes (“). This is probably not a surprise to you if you’ve seen PowerShell scripts before.

A “best practice” in PowerShell is that you should always default to using single-quotes unless you specifically need to use double-quotes. The reasons to use double-quotes are:

  • To enable substitution in the string (variables or expressions)
  • To utilize escape sequences in the string (introduced by backtick `)
  • To simplify embedding single-quotes in the string (without doubling the single quotes)

I have to admit, I find myself getting lazy about this and switching between types of quotes with no rhyme or reason. In fact, sometimes I see that I’m using double-quotes as the default just in case I end up doing variable substitution. In my opinion, however, this is not something I should be doing.

Here’s a post from Don Jones about quoting.

Anyone disagree with this one?

2 Comments

  1. I’m inclined to disagree. I’ve been doing just a bit of searching, and there seems to be an echo chamber on the internet about the use of single vs double quotes. “You should use single quotes” seems to be said everywhere, but without reason.

    People mention what double quotes can do: replace variables, allow for single quotes in the string, allow for escape characters. Although I may not need to do these with most strings, I also do not need the literal $variable text in my string either most of the time, and in fact need the literal variable name much less often than I need the value(s) for the variable(s) to be in my string.

    So I challenge this convention. Why not use double quotes by default? If there is some obvious reason why single quotes are the standard, why doesn’t anyone write what that reason is? Is it performance? Until I know a real reason, I will use double quotes as my standard, and I will find myself switching between types of quote characters much less often than others around me.

    • I appreciate you taking the time to reply, and I completely agree. One of the reasons this “series” stopped after #1 is that I had the same kind of thought going around in my head after writing this. Why shouldn’t you default to double quotes unless you specifically don’t want variable replacement (or escape characters)?

      I think your observation of an “echo chamber” is also somewhat accurate. It’s easy to simply take what experts say as a given, especially in the area of best practices. It’s often subjective as to what benefits are achieved by using a particular practice, in terms of maintainability, readability, extensibility etc. In this case, however, I’m not seeing any benefits to not using double quotes as the default.

      Thanks for speaking up.

      Mike

Comments are closed.