[英]Add double quotes to variable to escape space
I am running a script which has $FileName variable containing the absolute path with spaces. 我正在运行一个脚本,其中包含$ FileName变量,其中包含带空格的绝对路径。 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. 我只需要在双引号中添加$ FilePath。 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: 当前OutPut:
X:\Movies\File One\File One.txt
In addition to the backtick escape character ( `
), you can use the -f
format operator: 除了反引号转义字符( `
),您还可以使用-f
格式运算符:
$FilePath = Join-Path $Dir -ChildPath "$File.txt"
$FilePathWithQuotes = '"{0}"' -f $FilePath
This will ensure that $FilePath
is expanded before being placed in the string 这将确保$FilePath
在放入字符串之前进行扩展
$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. 当然,如果你想引用的路径本身可以包含"
引号"
,例如将来的“powershell for linux”,你需要以特定于上下文的方式转义"
。
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
fastest solution (but a bit ugly) to add quotes around any string: 在任何字符串周围添加引号的最快解决方案(但有点难看):
$dir = "c:\temp"
$file = "myfile"
$filepath = [string]::Join("", """", $dir,"\", $file, ".txt", """")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.