Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add double quotes to variable to escape space

Tags:

powershell

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
like image 958
user3331975 Avatar asked Feb 10 '16 07:02

user3331975


People also ask

How can I add double quotes to a string that is inside a variable?

The basic double-quoted string is a series of characters surrounded by double quotes. If you need to use the double quote inside the string, you can use the backslash character.

How do you use double quotes in a variable?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

How do you escape a double quote?

“Double quotes 'escape' double quotes“ When using double quotes "" to create a string literal, the double quote character needs to be escaped using a backslash: \" .


1 Answers

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

like image 68
Mathias R. Jessen Avatar answered Nov 07 '22 11:11

Mathias R. Jessen