Share via


Using double quotes within a string

Question

Thursday, July 28, 2011 5:31 PM

Hello all,

I am writing a script that will delete a file in a directory, then add a file with given text to that directory. My problem is in the 'given text' I need to use double quotes in the string. What happends is the code sees the inner set of double quotes and ends the string. Is there another way to mark off the string?

This is what i have:

$supportName = Read-Host "Message to user:"

IF ($supportName = "UserInput")
{
    remove-item C:\..\..\test.txt
    new-item -path C:\..\..\test.txt -value "Example text =- "innerExample" end string example" -itemtype file
}

I need the string to have the quotes exactly how it is because it is code being inserted that will be used by some software. Otherwise is there a method of finding a file name (like testfile.txt) in a files text somewhere and changeing it to say newtestfile.txt? This would also fix my problem.

All replies (6)

Thursday, July 28, 2011 5:55 PM ✅Answered

I'd use a here-string (either double or single quoted)

That will keep all the quoting intact, and avoid having to do any escaping or mental parsing to figure out which quotes the parser will leave and which ones it will strip off. 

http://technet.microsoft.com/en-us/library/ee692792.aspx

$example = @'
Example text =- "innerExample" end string example
'@

$supportName = Read-Host "Message to user:"

IF ($supportName = "UserInput")
{
    remove-item C:\..\..\test.txt
    new-item -path C:\..\..\test.txt -value $example -itemtype file
}

[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "


Thursday, July 28, 2011 10:51 PM ✅Answered

And also, replacing "double quotes" with "single quotes",

 

in a string quoted with single quotes, any embedded single quote

characters should be doubled.

 

$Value = 'If $Name is not correct, enter ''N'', otherwise enter ''Y'''

 

On 7/28/2011 4:43 PM, Richard Mueller wrote:

> Also, in a string quoted with double quotes, any embedded double quote

> characters should be doubled. That is, "" in the quoted string will

> resolve into ". For example:

>

> $Value = "If $Name is not correct, enter ""N"", otherwise enter ""Y"""

>

 


Thursday, July 28, 2011 11:38 PM ✅Answered

Also replace your if statement with

IF ($supportName -eq $supportName)

the = sign won;t work


Friday, July 29, 2011 2:47 AM ✅Answered

Use the backtick to escape:

"`""

Thursday, July 28, 2011 5:52 PM

Use single quotes around the string that contains double quotes.

 


Thursday, July 28, 2011 7:48 PM

Right, even doubled up quotes are left alone in here-strings.