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 ex
$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.
fastest solution (but a bit ugly) to add quotes around any string:
$dir = "c:\temp"
$file = "myfile"
$filepath = [string]::Join("", """", $dir,"\", $file, ".txt", """")
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
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