user3331975
user3331975

Reputation: 2805

Add double quotes to variable to escape space

I am running a script which has $FileName variable containing the absolute path with spaces. Due to the space within the directory name and file name, the script fails to executes without finding the actual path. All I need is to add $FilePath within double quotes. How should I append double quotes in the beginning and end of a string?

For example

"X:\Movies\File One\File One.txt"

Script:

$FilePath = Join-Path $Path $($Dir + "\" + $File + “.txt”)
$FilePath

Current OutPut:

X:\Movies\File One\File One.txt

Upvotes: 11

Views: 35709

Answers (4)

Carsten
Carsten

Reputation: 2191

fastest solution (but a bit ugly) to add quotes around any string:

$dir = "c:\temp"
$file = "myfile"
$filepath = [string]::Join("", """", $dir,"\", $file, ".txt", """")

Upvotes: 0

Baodad
Baodad

Reputation: 2491

Any one of these should work:

$FilePath1 = """" + (Join-Path $Path $($Dir + "\" + $File + ".txt")) + """"
$FilePath2 = "`"" + (Join-Path $Path $($Dir + "\" + $File + ".txt")) + "`""
$FilePath3 = '"{0}"' -f (Join-Path $Path $($Dir + "\" + $File + ".txt"))
$FilePath4 = '"' + (Join-Path $Path $($Dir + "\" + $File + ".txt")) + '"'
$FilePath5 = [char]34 + (Join-Path $Path $($Dir + "\" + $File + ".txt")) + [char]34

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

In addition to the backtick escape character (`), you can use the -f format operator:

$FilePath = Join-Path $Dir -ChildPath "$File.txt"
$FilePathWithQuotes = '"{0}"' -f $FilePath

This will ensure that $FilePath is expanded before being placed in the string

Upvotes: 12

Joachim Isaksson
Joachim Isaksson

Reputation: 180887

$FilePath = Join-Path $Path $($Dir + "\" + $File + “.txt”)
"`"$FilePath`""

...would output...

"X:\Movies\File One\File One.txt"

This is an example of variable expansion in strings.

Of course, if the path you want to quote could contain " quotes itself, for example in a future "powershell for linux", you'd need to escape the " in a context specific way.

Upvotes: 2

Related Questions