Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between single quote and double quote to define a string in powershell

Tags:

powershell

Simple questions that's been bugging me: In powershell, I can define strings like so:

$s1 = "Boogety boo" 

or

$s2 = '.net rocks' 

Is there a difference to the interpreter?

like image 692
Dave Harding Avatar asked May 11 '11 16:05

Dave Harding


People also ask

What is the difference between single quotes and double quotes string?

A single-quoted string does not have variables within it interpreted. A double-quoted string does. Also, a double-quoted string can contain apostrophes without backslashes, while a single-quoted string can contain unescaped quotation marks.

What do double quotes mean in PowerShell?

Double-quoted stringsA string enclosed in double quotation marks is an expandable string. Variable names preceded by a dollar sign ( $ ) are replaced with the variable's value before the string is passed to the command for processing. For example: PowerShell Copy. $i = 5 "The value of $i is $i."

How do you pass double quotes in a PowerShell string?

This means that if you hard code a Distinguished Name in PowerShell, and the string is enclosed in double quotes, any embedded double quotes must be escaped first by a backtick "`", and then by a backslash "\".

How do I quote a string in PowerShell?

To include the double quotes inside of the string, you have two options. You can either enclose your string in single quotes or escape the double quotes with a symbol called a backtick. You can see an example of both below of using PowerShell to escape double quotes. Notice that "string" now includes the double quotes.


2 Answers

Double quotes allow variable expansion while single quotes do not:

PS C:\Users\Administrator> $mycolor="red" PS C:\Users\Administrator> write-output -inputobject 'My favorite color is $mycolor' My favorite color is $mycolor 

Source: http://www.techotopia.com/index.php/Windows_PowerShell_1.0_String_Quoting_and_Escape_Sequences

(I know version 1.0 but the principle is still the same)

like image 61
onteria_ Avatar answered Oct 13 '22 21:10

onteria_


This is not trying to be a better answer. Just another way to say it.

The variable expansion between apostrophes and quotes are the same as on UNIX shells (sh, ksh, bash). Using apostrophes will take the character string as-is, without processing any escapes.

PS C:\Users\lit> $x = "`t" PS C:\Users\lit> $x  PS C:\Users\lit> Write-Output "now${x}is" now     is PS C:\Users\lit> $x = '`t' PS C:\Users\lit> $x `t PS C:\Users\lit> Write-Output "now${x}is" now`tis PS C:\Users\lit> $word = "easy" PS C:\Users\lit> "PowerShell is $word" PowerShell is easy PS C:\Users\lit> 'PowerShell is $word' PowerShell is $word 
like image 35
lit Avatar answered Oct 13 '22 21:10

lit