Add double quotes to variable to escape space

后端 未结 4 1652
遇见更好的自我
遇见更好的自我 2020-12-20 22:02

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

相关标签:
4条回答
  • 2020-12-20 22:39
    $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.

    0 讨论(0)
  • 2020-12-20 22:39

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

    $dir = "c:\temp"
    $file = "myfile"
    $filepath = [string]::Join("", """", $dir,"\", $file, ".txt", """")
    
    0 讨论(0)
  • 2020-12-20 22:46

    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 讨论(0)
  • 2020-12-20 22:48

    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 讨论(0)
提交回复
热议问题