10

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
2
  • does this work for you? "'$path\$dir\$file.txt'" Feb 10, 2016 at 7:24
  • $FilePath = Join-Path $Path $($Dir + "\" + $File + ".txt") could be re-written as $FilePath = Join-Path $Path (Join-Path $Dir ($File + ".txt"))
    – Baodad
    Jul 5, 2018 at 20:45

4 Answers 4

11

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

0
2
$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.

1
  • 1
    Presumably the curly quotes here were mistaken? Mar 21, 2018 at 12:51
0

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
0

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.