Difference between single quotes and double quotes in PowerShell


If you are new to PowerShell you may find the use of ‘ and " for enclosing strings confusing. Both single quotes and double quotes can be used to enclose a string. There is a difference and it is best to demonstrate this by example

$fruit = 'peaches, apples and mangoes'
$singleQuoteText = 'I like $fruit'
$doubleQuoteText = "I like $fruit"

# Produces the output:
# I like $fruit
Write-Output $singleQuoteText

# Produces the output:
# I like peaches, apples and mangoes
Write-Output $doubleQuoteText

When using single quotes the text appears as you specify it between the single quotes – what you read is what you get. When using double quotes you have the ability to format the string with the value of a variable by specifying the variable name in the string. The output will include the value of the variable and not the name of the variable as is the case with single quotes.

For consistency, the standard I use when deciding which enclosing character to use is

  • Use single quotes by default when dealing with string literals
  • Only use double quotes when you need to format a string with the value of a variable

Another question you may have is how do I include quotes within quotes. This can be done by specifying two quotes within the quoted text. The example above has been modified to demonstrate this

$fruit = 'peaches, apples and mangoes'
$singleQuoteText = '''I like $fruit'' John said.'
$doubleQuoteText = """I like $fruit"" John said."

# Produces the output:
# 'I like $fruit' John said.
Write-Output $singleQuoteText

# Produces the output:
# "I like peaches, apples and mangoes" John said.
Write-Output $doubleQuoteText

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: